题目链接
思路
与 【DFS】LeetCode 40. 组合总和 II 思路一致,只不过 candidates
数组在题目中明确说明了只有1到9。
代码
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private Deque<Integer> path = new ArrayDeque<>();
private int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
dfs(1, n, k);
return result;
}
void dfs(int index, int target, int k) {
if(sum > target || path.size() > k){
return;
}
if(path.size() == k){
if(sum == target){
result.add(new ArrayList<>(path));
}
return;
}
for(int i = index; i <= 9; i++){
sum += i;
path.addLast(i);
dfs(i + 1, target, k);
path.removeLast();
sum -= i;
}
}
}
标签:216,int,sum,private,DFS,path,III,result
From: https://www.cnblogs.com/shixuanliu/p/17182715.html