40. 组合总和 II
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
注意几点:
1,有重复的值。先排序这样可以更好的处理重复组合
2,每个值只能用一次,所以传入到下一层的是i+1
// 不同点:1, 有重复的,需要排序了;2,只能用一次,下一层的传参是i+1
Stack<Integer> stack = new Stack<>();
List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// 一定要先排序
Arrays.sort(candidates);
dfs(candidates,target,0);
return ret;
}
public void dfs(int[] candidates, int target, int index) {
if(target < 0) {
return;
}
if(target == 0) {
ret.add(new ArrayList<>(stack));
return;
}
for(int i=index;i<candidates.length;i++) {
// 由于数字有重复,所以如果后一个和前一个是同树,那么就跳过
if(i-1>=index && candidates[i-1] == candidates[i]) {
continue;
}
stack.push(candidates[i]);
// 传给下一个层的要i+1
dfs(candidates,target-candidates[i],i+1);
stack.pop();
}
}