解题思路
dfs,和全排列的写法类似。
相关代码
class Solution {int a[] = new int[9];List<Integer> path = new ArrayList<>();boolean st[] = new boolean[10];List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> combinationSum3(int k, int n) {for(int i=0;i<a.length;i++) a[i] = i+1;dfs(a,0,k,n,path);return res;}public void dfs(int a[],int u,int k,int n,List<Integer> path){if(path.size()==k){int s=0;for(int i=0;i<path.size();i++){s=s+path.get(i);}if(s==n){res.add(new ArrayList<>(path));return;}}for(int i=u;i<a.length;i++){if(st[i]==false){st[i]=true;path.add(a[i]);dfs(a,i+1,k,n,path);st[i]=false;path.remove(path.size()-1);}}}}