LeetCode77-20.9.8-组合

这篇博客探讨了LeetCode第77题的解决方法,博主在解决过程中遇到了思维障碍,但通过复习组合知识并参考题解,理解了问题的本质。文章重点介绍了通过枚举状态来解决问题的思路。
摘要由CSDN通过智能技术生成

链接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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值