文章目录
- 题目介绍
- 解法
题目介绍
解法
是216组合总和III链接的扩展
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, target, 0, 0);
return res;
}
private void dfs(int[] candidates, int target, int startIndex, int sum) {
if (sum >= target) {
if (sum == target) {
res.add(new ArrayList<>(path));
}
return;
}
for (int i = startIndex; i < candidates.length; i++) {
path.add(candidates[i]);
sum += candidates[i];
// 关键点:不用i+1了,表示可以重复读取当前的数
dfs(candidates, target, i, sum);
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}