39.组合总和
分析
- 以 target = 7 为 根结点 ,创建一个分支的时 做减法 ;
- 每一个箭头表示:从父亲结点的数值减去边上的数值,得到孩子结点的数值。边的值就是题目中给出的 candidate 数组的每个元素的值;
- 减到 0 或者负数的时候停止,即:结点 0 和负数结点成为叶子结点;
- 所有从根结点到结点 0 的路径(只能从上往下,没有回路)就是题目要找的一个结果。
- 这棵树有 4 个叶子结点的值 0,对应的路径列表是 [[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]],而示例中给出的输出只有 [[7], [2, 2, 3]]。即:题目中要求每一个符合要求的解是 不计算顺序 的。
- 可不可以在搜索的时候就去重呢?答案是可以的。遇到这一类相同元素不计算顺序的问题,我们在搜索的时候就需要 按某种顺序搜索。具体的做法是:每一次搜索的时候设置 下一轮搜索的起点 begin,
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
dfs(candidates, 0, target, path, res);
return res;
}
public void dfs(int[] candidates, int begin, int target, Deque<Integer> path, List<List<Integer>> res) {
if(target < 0) return;
if(target == 0) {
res.add(new ArrayList<>(path));
return;
}
for(int i = begin; i < candidates.length; i++) {
path.addLast(candidates[i]);
dfs(candidates, i, target - candidates[i], path, res);
path.removeLast();
}
}
}