回溯算法,按照之前的思路我列了一个1-9的数组
class Solution {
List<List<Integer>> res=new ArrayList<>();
int [] candidates={1,2,3,4,5,6,7,8,9};
public List<List<Integer>> combinationSum3(int k, int n) {
if(n==0) return res;
List<Integer> path=new ArrayList<>();
backstrack(k,n,path,0);
return res;
}
public void backstrack(int k,int n,List<Integer> path,int begin){
if(n==0&&k==0){
res.add(new ArrayList<>(path));
return ;
}
for(int i=begin;i<candidates.length;i++){
if(candidates[i]<=n){
path.add(candidates[i]);
//不允许重复,因此从i+1开始
backstrack(k-1,n-candidates[i],path,i+1);
path.remove(path.size()-1);
}
}
}
}
效率竟然不低