思路回溯算法
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> totalResult=new ArrayList<List<Integer>>();
int record[]={0,0,0,0,0,0,0,0,0,0};
process(k, n, record, 1, 0, totalResult);
return totalResult;
}
public void process(int k,int n,int record[],int i,int currentsum,List<List<Integer>> totalResult)
{
if(i>9)
{
return;
}
k--;
record[i]=1;
if(currentsum+i==n&&k==0)
{
List<Integer> result=new ArrayList<Integer>();
for(int j=0;j<10;j++)
{
if(record[j]==1)
{
result.add(j);
}
}
totalResult.add(result);
record[i]=0;
return;
}
currentsum+=i;
if(currentsum<n&&k>0)
{
process(k, n, record, i+1, currentsum, totalResult);
}
record[i]=0;
currentsum-=i;
k++;
process(k, n, record, i+1, currentsum, totalResult);
return;
}
}
别人的算法
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
recur(new ArrayList<Integer>(),res,n,1,k);
return res;
}
public void recur(List<Integer> temp,List<List<Integer>> res, int tar,int k,int count){
if(tar==0&&count==0){
res.add(temp);
return;
}
if(count==0||tar<=0)return;
for(int i=k;i<=9;i++){
temp.add(i);
recur(new ArrayList<Integer>(temp),res,tar-i,i+1,count-1);
temp.remove(temp.size()-1);
}
}
}