链接: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;
}
}
LeetCode77:组合问题解析
这篇博客探讨了LeetCode第77题的解决方法,博主在解决过程中遇到了思维障碍,但通过复习组合知识并参考题解,理解了问题的本质。文章重点介绍了通过枚举状态来解决问题的思路。
8521

被折叠的 条评论
为什么被折叠?



