leetcode40. 组合总和 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]
]

代码

class Solution {
    List<List<Integer>> ret=new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);//排序
        combination(candidates,0,target,new LinkedList<>());
        return  ret;
    }
    public void combination(int[] candidates, int loc, int target, LinkedList<Integer> temp) {
        if(target==0){//符合情况
            ret.add((List<Integer>) temp.clone());
            return;
        }
        for(int i=loc;i<candidates.length;i++)//以后面不同节点接上去
        {
            if(candidates[i]>target) continue;//不满足情况
            if(i>loc&&candidates[i]==candidates[i-1]) continue;//相同的头节点
            temp.add(candidates[i]);
            combination(candidates, i+1, target-candidates[i], temp);//计算后面的子问题
            temp.removeLast();//回溯
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107701591