题目链接
思路:深搜+回溯
分析:因为每个数字都可以用多次,也就是说要找到所有的可行解,那么这里使用的是搜索+回溯的方法来解决。
这里定义了dfs函数。
第一个参数是:排好序的candidates。
第二个参数是:当前需要凑出来的目标值。
第三个参数是:当前从candidates数字开始遍历的下标。
第四个参数是:candidates的长度。
dfs:函数功能是查找[index.n-1]范围内,能凑出tar的组合。
这里要注意,因为candidates中的元素都是正数,所以一旦最开始的元素就大于了tar,那么就可以直接跳出,就减枝了。
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> seqr = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates, target, 0, candidates.length);
return res;
}
//寻找出[index,n-1]的范围内能凑出tar的组合
public void dfs(int[] candidates, int tar, int index, int n){
if(tar==0){
//目标为0,说明此时已经找到了组合
//这里要注意,因为candidates中的元素都是整数,所以后面不会出现好几个数字相加为0的情况。
//素以此时一旦满足了tar等于0,那么加入结果集后,直接返回
res.add(new ArrayList<>(seqr));
return ;
}
if(candidates[index]>tar){
return;
}
for(int i=index; i<n; i++){
seqr.add(candidates[i]);
dfs(candidates, tar-candidates[i], i, n);
seqr.remove(seqr.size()-1);
}
}
}