https://leetcode.cn/problems/combination-sum-iii/description/
class Solution {
ArrayList<List<Integer>> res=new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
find(new ArrayList<Integer>(),1,0,k,n,0);//从数字1开始寻找
//sum=0,count=0,k,n
return res;
}
//num:下一个准备选的数字
public void find(ArrayList<Integer> tmp,int num,int sum,int k,int n,int count){
if(count==k){//是k个数,不能再继续增加数量了
if(sum==n){//和为n,找到一个结果
res.add(new ArrayList<>(tmp));
}
return;
}
//或许有剪枝?
if(num>9) return;
//i代表遍历到的当前数字
for(int i=num;i<=9;i++){
tmp.add(i);//加入当前数字i
find(tmp,i+1,sum+i,k,n,count+1);//下次遍历不能用当前数字i,只能从i+1开始
tmp.remove(tmp.size()-1);//回溯,移除末尾元素
}
}
}