https://leetcode.cn/problems/combination-sum/description/
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
解法一(java):
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backTrack(0,result,candidates,target,new ArrayList<>());
return result;
}
public void backTrack(int index,List<List<Integer>> result,int[] candidates,int target,List<Integer> tmp) {
if (target == 0) {
result.add(new ArrayList<>(tmp));
return;
}
if (target < 0) {
return;
}
for (int i = index; i < candidates.length ; i++) {
int v = candidates[i];
tmp.add(v);
backTrack(i,result,candidates,target - v,tmp);
tmp.remove(tmp.size() - 1);
}
}
}
思路:回溯法,参考http://www.haijin.xyz/article/566
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择 : 本层集合中的元素) {
处理节点;
backtracking(路径, 选择列表); // 递归
撤销处理; // 回溯
}
}
回溯框架:
使用递归回溯的方法系统地探索所有可能的数字组合
通过深度优先搜索(DFS)遍历决策树
递归终止条件:
当 target == 0 时,找到有效组合,加入结果集
当 target < 0 时,当前路径无效,直接返回
数字选择逻辑:
从当前 index 开始遍历候选数组
每个数字可以被无限次重复使用(通过传递 i 而非 i+1 给下一层递归)
通过控制 index 避免生成顺序不同但元素相同的重复组合
关键点分析
允许重复使用数字:
backTrack(i, ...) 保持索引不变,使得当前数字可以被重复选择
这是与组合总和II问题的主要区别(后者用i+1)
避免重复组合:
通过每次从 index 开始遍历,自然避免了像[2,2,3]和[2,3,2]这样的重复组合
保证组合是按非递减顺序生成的
剪枝优化:
target < 0 时的提前返回避免了不必要的递归调用
虽然没有显式排序,但按数组顺序选择也起到了类似效果
执行流程示例
以 candidates = [2,3,6,7], target = 7 为例:
选择2 (剩余5)
再选2 (剩余3)
再选2 (剩余1)
选2 (剩余-1) → 返回
选3 (剩余0) → 得到[2,2,3]
选3 (剩余2) → ...
选3 (剩余4) → ...
选6 (剩余1) → ...
选7 (剩余0) → 得到[7]