LeetCode 39. 组合总和

39. 组合总和

解题思路

start 下标开始遍历候选数,每次可选当前数「可重复选,因此递归仍传当前下标 i」并扣减目标值,目标值为 0 时记录组合,回溯后尝试下一个数,避免重复组合

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
private List<List<Integer>> res = new ArrayList<>();
private List<Integer> tmp = new ArrayList<>();

public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, target, 0, res, tmp);
return res;
}

private void dfs(int[] candidates, int target, int start, List<List<Integer>> res, List<Integer> tmp) {
if(target == 0) {
res.add(new ArrayList<>(tmp));
return;
}
for(int i = start; i < candidates.length; i ++) {
if(target - candidates[i] >= 0) {
tmp.add(candidates[i]);
dfs(candidates, target - candidates[i], i, res, tmp);
tmp.remove(tmp.size() - 1);
}
}
}
}

LeetCode 39. 组合总和
https://sowink.cn/2026/02/08/LeetCode-39-组合总和/
作者
Xurx
发布于
2026年2月8日
许可协议