LeetCode:组合总和II

题目:

给定一个数组 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]
]

我的答案:

回溯,跟上一题思路一样,但是需要去重,添加了一个while语句来处理,代码如下:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates==null||candidates.length==0){
            return null;
        }
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        reComSum2(candidates,target,result,list,0);
        return result;
    }

    public void reComSum2(int[] candidates,int target,List<List<Integer>> result,List<Integer> list,int left){
        if(target==0){
            result.add(list);
            return;
        }
        if(left>candidates.length-1||target<candidates[left]){
            return;
        }
        for(int i=left;i<candidates.length;i++){
            ArrayList<Integer> newList = new ArrayList<>();
            newList.addAll(list);
            newList.add(candidates[i]);
            //下面是i+1,避免一个数字重复使用
            reComSum2(candidates,target-candidates[i],result,newList,i+1);
            //while循环来去重
            while(i+1<candidates.length&&(candidates[i]==candidates[i+1])){
                i++;
            }
        }
    }
}

题解:

参考上一题

总结:

回溯!!!

发布了75 篇原创文章 · 获赞 2 · 访问量 8003

猜你喜欢

转载自blog.csdn.net/wyplj2015/article/details/104807206