77. 组合
class Solution {
private int k;
private final List<Integer> path = new ArrayList<>();
private final List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
this.k = k;
dfs(n);
return ans;
}
private void dfs(int startIndex ){
int d = k - path.size();
if(d == 0 ){
ans.add(new ArrayList<>(path));
return;
}
for(int j = startIndex ; j >= d ; --j){
path.add(j);
dfs(j - 1);
path.removeLast();
}
}
}
216.组合总和III
class Solution {
private int k;
private final List<Integer> path = new ArrayList<>();
private final List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
dfs(9,n);
return ans;
}
private void dfs(int startIndex , int target){
int d = k - path.size();
if (target < 0 || target > (startIndex * 2 - d + 1) * d / 2) // 剪枝
return;
if (d == 0) {
ans.add(new ArrayList<>(path));
return;
}
for(int j = startIndex ; j >= d ; --j){
path.add(j);
dfs(j-1,target-j);
path.removeLast();
}
}
}