1. 问题描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
2. 解题思路
参考链接:
https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-2/
以 输入:candidates = [2, 3, 6, 7], target = 7 为例:
① 以 7 为根节点,创建分支的时候做减法
② 从每一个父亲节点开始减去 candidates 数组中的一个值,得到该节点的子节点
③ 当子节点的值为 0 或者负数的时候停止创建分支
④ 从根节点到节点 0 的路径的全集即为题目所求
针对重复路径
产生的解决方法:
在搜索的时候就去重,即每一次搜索的时候设置下一轮搜索的起点 begin,从每一层的第二个节点开始,都不能再搜索同一层节点已经使用过的candidates里面的元素。
3. 代码实现
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
int len = candidates.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0) {
return res;
}
Arrays.sort(candidates);
Deque<Integer> path = new ArrayDeque<>();
dfs(candidates, 0, len, target, path, res);
return res;
}
private void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res) {
// 递归出口:当进入更深层时,小于0的部分会被剪枝
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i < len; i++) {
if (target - candidates[i] < 0) {
break;
}
path.addlast(candidates[i]);
dfs(candidates, i, len, target - candidates[i], path, res);
path.removeLast();
}
}
}