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;
    }
};


原文地址:https://www.cnblogs.com/mfrbuaa/p/3826188.html