题目描述:
标签:数组 回溯算法
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
代码:
思路分析:思路同 组合求和Ⅲ
不过要注意的就是因为可以重复取用,所以在递归时候注意是backTracing(candidates,target,sum,i)是i不是i+1!
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backTracing(candidates,target,0,0);
return result;
}
public void backTracing(int[] candidates,int target,int sum,int startIndex){
if(sum > target){
return;
}
if(sum == target){
result.add(new ArrayList<>(path));
return;
}
for(int i = startIndex;i < candidates.length;i++){
sum += candidates[i];
path.add(candidates[i]);
backTracing(candidates,target,sum,i);//不用i+1表示可以重复取当前元素
sum -= candidates[i];
path.remove(path.size()-1);
}
}
}