2020_9_8每日一题 组合

给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3],
[1,4], ]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

经典回溯,每一个位置的有选择和不选择两个分支,分别向后前进就好。一个可行的优化是,如果剩下的数比要找的数少,就可以不再往前走了:

class Solution {
    void process(int cur, int n, int curK, int k, LinkedList<Integer> res, List<List<Integer>> ans) {
        //分别处理要这个数和不要这个数的情形
        if(cur > n || n - cur + 1 < k - 1 - curK)
            return;

        //要这个数
        res.add(cur);
        if(curK == k - 1) {
            ans.add(new LinkedList<Integer>(res));
        } else if(curK < k - 1){
            process(cur + 1, n, curK + 1, k, res, ans);
        }

        //不要这个数
        res.removeLast();
        process(cur + 1, n, curK, k, res, ans);
    }

    public List<List<Integer>> combine(int n, int k) {
        //回溯算法?总之挺蛋疼的
        List<List<Integer>> ans = new LinkedList<>();
        LinkedList<Integer> res = new LinkedList<>();
        if(k > n)
            return ans;
        
        process(1, n, 0, k, res, ans);
        return ans;
    }
}

题解除了这种方法之外给出了一种从上一个序列推导下一个序列的方法。从做往右遍历,直到发现不连续为止。发现的连续序列的前若干个置位置+1,最后一个+1。
以n = 8, k = 4为例
1234 => 1235
4567 => 1238
1267 => 1367
这样是能保证不重不漏的,从上面就可以看出来,把整个串当成一个数,下一个数就是比上一个数大的最小的满足条件的数(从右往左看,满足条件指高位总比低位大)。
尝试实现一下:

class Solution {
    List<Integer> next(List<Integer> cur, int n, int k) {
        List<Integer> ret = new LinkedList<>(cur);
        int i;
        for(i = 0; i < k - 1 && cur.get(i) + 1 == cur.get(i + 1); ++i) {
            ret.set(i, i + 1);
        }
        if(ret.get(i) == n) {
            ret = null;
        } else {
            ret.set(i, ret.get(i) + 1);
        }
        return ret;
    }

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        for(int i = 1; i <= k; ++i) {
            res.add(i);
        }
        do{
            ans.add(res);
            res = next(res, n, k);
        } while(res != null);
        return ans;
    }
}

题解里头用了花里胡哨的哨兵,智力不够理解不太了(也是懒得去理解了),不过我这么做也彳亍口巴。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值