Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II)

Leetcode之回溯法专题-40. 组合总和 II(Combination Sum 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]
]


分析:跟上一题(Leetcode.39)类似,区别在于这题每个数字只能用一次。还是同样的思想(回溯法),
大于target的直接跳过,先排序。

回溯法 -> 举例
candidates = [10,1,2,7,6,1,5], target = 8 , 排序后candidates = [1,1,2,5,6,7,10]
首先,入口是dfs(index=0)
选第一个1,这里我们标记为step1,
接着继续选取第二个1,标记为step2,
继续选2,step3,
选5,标记为step4,
此时已超出target=8(此时为9),故大于了target,根据代码return到上一步,返回到step4,不选5,选6
超出,退回,不选6,选7,超出,退回,选10,超出,退回。(我的AC代码里在后面还是循环了,所以浪费了很多时间,可以发现大于的就直接返回,不进入下一步了)

以此类推。因此第一个产生出来的答案应该是 1 2 5



AC代码:
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates,target,0,target,new ArrayList<Integer>());
        return ans;
    }
    
    
    public void dfs(int[] candidates,int target,int index,int balance,ArrayList<Integer> list){
        if(balance<0){
            return;
        }
        if(balance==0){
            if(!ans.contains(list)) ans.add(new ArrayList<Integer>(list));
            return;
        }
        
        if(index>=candidates.length){
            return;
        }
        int num = candidates[index];
        
        list.add(num);
        dfs(candidates,target,index+1,balance-num,list);
        list.remove(list.size()-1);
        dfs(candidates,target,index+1,balance,list);

    }
}
 
 
 











猜你喜欢

转载自www.cnblogs.com/qinyuguan/p/11318820.html