组合总和 II(剪枝算法)
ps:做这道题之前需要先明白<组合总和>
题目
给定一个数组 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]
]
解题
思路
参考<组合总和>的解题思路,这里有两点不同:
- 元素不能重复利用,所以每次向下递归的时候的不能是i,应该是i+1
- 如果只改1的话,你会发现有重复的,因为数字有重复的话(而这个数字又恰好在答案里面,那么这个答案势必会重复)
诀窍就是,同一行的决策树是不能有重复数字的,有的话就跳过(也就是循环中)
代码
class Solution {
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
LinkedList<Integer> track = new LinkedList<>();
combinationSum2(candidates, 0, target, track);
return result;
}
private void combinationSum2(int[] candidates, int start, int target, LinkedList<Integer> track) {
if (target < 0) {
return;
} else if (target == 0) {
result.add(new LinkedList<>(track));
return;
}
for (int i = start; i < candidates.length; i++) {
int candidate = candidates[i];
if (target < candidate) {
break;
}
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
track.add(candidate);
combinationSum2(candidates, i + 1, target - candidate, track);
track.removeLast();
}
}
}