链接:LeetCode77
过程:怎么感觉脑子如此生涩,回忆起组合的知识,习惯性看题解。理解简单,开始的时候想难。。。
思路:枚举状态
代码:
class Solution {
List<List<Integer>> ans=new ArrayList<>();
List<Integer> temp=new ArrayList<>();
int n,k;
public List<List<Integer>> combine(int n, int k) {
this.n=n;
this.k=k;
dfs(1,0);
return ans;
}
private void dfs(int cur,int cnt){
if(cnt+n-cur+1<k)return;
if(cnt==k){
ans.add(new ArrayList(temp));
return;
}
if(cur>n)return;
temp.add(cur);
dfs(cur+1,cnt+1);
temp.remove(cnt);
dfs(cur+1,cnt);
}
}
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans=new ArrayList<>();
List<Integer> temp=new ArrayList<>();
for(int i=1;i<=k;i++)temp.add(i);
temp.add(n+1);
int j=0;
while(j<k){
ans.add(new ArrayList<>(temp.subList(0,k)));
j=0;
while(j<k&&temp.get(j)+1==temp.get(j+1)){
temp.set(j,j+1);
j++;
}
temp.set(j,temp.get(j)+1);
}
return ans;
}
}