题目:
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
解题思路:
总体上这道题采用回溯的方法解决。主要有几点细节:
1、需要记录path中的元素和sum,当sum==target,就是收获结果并结束递归的时候;同时当sum>target时,说明后面已经不可能找到和为target的path了,也需要结束递归。
2、因为是求组合,那么结果和元素顺序无关,所以回溯方法的参数需要一个startIdx记录当前层的选择元素的开始索引。
3、因为同一个数字可以无限制重复被选取,也就意味着上一层选取了的元素,下一层也可以选取,那么在递归调用backtrack的时候startIdx就保持不变。
4、恢复现场除了path需要恢复,sum也需要恢复。
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrack(candidates, target, 0, 0);
return result;
}
private void backtrack(int[] candidates, int target, int sum, int startIdx){
if(sum == target){
result.add(new ArrayList<>(path));
return;
}
if(sum > target){
return;
}
for(int i = startIdx; i < candidates.length; i++){
path.add(candidates[i]);
sum += candidates[i];
backtrack(candidates, target, sum, i);
path.removeLast();
sum -= candidates[i];
}
}
}