216.组合总和III
方法:回溯
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
dfs(ans,path,n,k,1);
return ans;
}
public void dfs(List<List<Integer>> ans,Deque<Integer> path,int target,int k,int begin){
if(target == 0 && path.size() == k){
ans.add(new ArrayList<Integer>(path));
return;
}
for(int i = begin;i< 10;i++){
if(target - i < 0) return;
path.addLast(i);
dfs(ans,path,target-i,k,i+1);
path.removeLast();
}
}
}