zoukankan      html  css  js  c++  java
  • LeetCode:Combinations

          Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.


    For example,


    If n = 4 and k = 2, a solution is:


    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]
    
    解题思路:
    
        首先,我们将该问题转换为求{1,2,3,....n}所包括的全部大小为k的子集.一般关于组合问题
    
    中的n值都不会太大,所以我选择用一个int变量的二进制位用来标记某个元素时候出现,然后通过
    
    从0枚举到(1 << n) - 1,就可以知道其全部的子集,因为子集大小为k,故需推断一下当前枚举
    
    值中1的个数时候为k.这样的方法显然是可行的,只是时间复杂度有点高O(2^n),那么,我们能不能枚举
    
    时,就仅仅枚举元素大小为k的子集?通过使用位运算我们能够非常easy的做到这点.
    
    解题代码:
    
    class Solution {
    public:
        vector<vector<int> > combine(int n, int k) 
        {
            vector<vector<int> > res;
            int comb = (1 << k) - 1;
            while (comb < 1 << n)
            {
                int tmp = comb, cnt = 1;
                vector<int> sub;
                while (tmp)
                {
                    if (tmp & 1)
                        sub.push_back(cnt);
                    ++cnt;
                    tmp >>= 1;
                }
                res.push_back(sub);
                //关键代码
                int x = comb & -comb, y = comb + x;
                comb = ((comb & ~y) / x >> 1) | y;
            }
            return res;
        }
    };
    


  • 相关阅读:
    PHP安装linux
    nginx 安装
    Redis安装
    linux启动http服务
    收藏的有用的网页
    laravel框架部署后有用命令
    .net 报错access to the path c: empimagefilesmsc_cntr_0.txt is denied
    oracle 触发器
    学习Auxre记录
    mysql数据库索引
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3826188.html
Copyright © 2011-2022 走看看