LeetCode:Combinations

来源:互联网 发布:淘宝客php源码下载 编辑:程序博客网 时间:2024/05/18 17:55

      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的子集?通过使用位运算我们可以很容易的做到这点.解题代码:
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;    }};


0 0
原创粉丝点击