快乐写代码

T40、数组总和II

2020-05-25  本文已影响0人  上行彩虹人

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]

需要对结果去重,所以最重要的一步是对数组排序

  List<List<Integer>> res;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        res = new LinkedList<>();
        Arrays.sort(candidates);
        find(candidates,0,new LinkedList(),target);
        return res;
    }

    public void find(int[] candidates,int idx,LinkedList<Integer> temp, int need){
        if(need==0 && !res.contains(temp)){
            res.add(new LinkedList<>(temp));
            return;
        }else if(need < 0)
            return;
       
        for(int i = idx; i < candidates.length; i++){
            temp.add(candidates[i]);
            need -= candidates[i];
            find(candidates,i+1,temp,need);
            // temp.remove(temp.removeLast()-1);
            temp.removeLast();
            need += candidates[i];
        }
    }

解2

 List<List<Integer>> res;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        res = new LinkedList<>();
        Arrays.sort(candidates);
        find(candidates,0,new LinkedList(),target);
        return res;
    }

    public void find(int[] candidates,int idx,LinkedList<Integer> temp, int need){
        if(need==0){
            res.add(new LinkedList<>(temp));
            return;
        }else if(need < 0)
            return;
       
        for(int i = idx; i < candidates.length; i++){
            // 判断当前元素是否已经被使用过了
            if(i > idx && candidates[i] == candidates[i-1])
                continue;
            temp.add(candidates[i]);
            need -= candidates[i];
            find(candidates,i+1,temp,need);
            // temp.remove(temp.removeLast()-1);
            temp.removeLast();
            need += candidates[i];
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读