题目:
思路:回溯
仍然,先排序,用目标值不断减去放入结果集合的数字,这样目标值与0比较即可判断是否找到解;
- 加速剪枝:回溯的过程中,如果目标值减去当前数字小于0,那么后面所有数字都不可能满足条件了(已经排序),此时直接返回;
- 跟上一题不同的是:数字不能重复使用,所以回溯搜索时要从下一个位置开始。
去重:同层不能有重复,不同层可以重复,即:
不能出现:
可以出现:
- 如何保证同层不重复呢?
candidates[i] == candidates[i - 1]
,然而这样也会剪掉不同层重复的情况 - 如何保证不同层可以重复呢?我们可以判断,当前位置的数字是不是第一个出现的,第一个出现,就有
i == begin
;不是第一个位置,就有i > begin
。
代码:
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList<>();
Arrays.sort(candidates);
backtrack(res, cur, candidates, 0, target);
return res;
}
public void backtrack(List<List<Integer>> res, List<Integer> cur, int[] candidates, int start, int target) {
if (0 == target) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = start; i < candidates.length; i++) {
// 剪枝
if (target - candidates[i] < 0) {
return;
}
// 去重
if (i > start && i - 1 >= 0 && candidates[i] == candidates[i - 1]) {
continue;
}
cur.add(candidates[i]);
// 不允许重复使用,从下一个位置i+1开始搜索
backtrack(res, cur, candidates, i + 1, target - candidates[i]);
cur.remove(cur.size() - 1);
}
}
}