题目:39. 组合总和
思路:回溯
为了方便后续处理,我们先排序。
-
我们用目标值不断减去放入结果集合的数字,这样目标值与0比较即可判断是否找到解;
-
加速剪枝:回溯的过程中,如果目标值减去当前数字小于0,那么后面所有数字都不可能满足条件了(已经排序),此时直接返回;
-
去重剪枝:这道题,数字可以重复使用,去重剪枝包含两块:
- (1)对于重复的数字,我们只考虑第一个,其余的全部跳过;
- (2)每一次的搜索都从当前位置开始,不考虑当前位置之前的数字,因为之前的数字已经搜索过了。
例1:1113,target = 4
例2:123, target = 5
代码:
class Solution {
public List<List<Integer>> combinationSum(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 - 1 >= 0 && candidates[i] == candidates[i - 1]) {
continue;
}
cur.add(candidates[i]);
// 数字可以重复使用,所以仍从当前位置i开始搜索。
backtrack(res, cur, candidates, i, target - candidates[i]);
cur.remove(cur.size() - 1);
}
}
}