组合总和
题目详细:LeetCode.39
由题可知:
- 给你一个
无重复元素的整数数组 candidates 和一个目标整数 target,找出 candidates 中可以使数字和为目标数 target 的所有不同组合 - candidates 中的
同一个数字可以无限制重复被选取。
所以可得:
- 递归的结束条件(回溯的条件)为,组合之和 == target,并将该组合放入结果集中
- 利用 for 循环依次累计 candidates 中数字的和 sum
- 当 sum <= target 时,那么 i 不变,继续递归重复累计当前数字,或保存和为 target 的组合结果
- 当 sum > target 时,那么直接回溯,i++,累计下一个数字
- 所以递归的参数(回溯的参数)有:整数数组 candidates 、目标整数 target、当前累计的数字之和 sum 和 当前累计的数字的下标 startNum。
Java解法(递归,回溯):
class Solution {
List<List<Integer>> ans = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
public void backtracking(int[] candidates, int target, int sum, int startNum){
if(sum == target){
ans.add(new ArrayList<>(path));
return;
}
for(int i = startNum; i < candidates.length; i++){
int num = candidates[i];
path.offer(num);
sum += num;
if(sum <= target){
backtracking(candidates, target, sum, i);
}
// else:如果已经sum > target了,那么直接回溯
// 回溯
path.removeLast();
sum -= num;
// i++:累计下一个数字
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(candidates, target, 0

最低0.47元/天 解锁文章
993

被折叠的 条评论
为什么被折叠?



