LeetCode:Combinations

來源:互聯網
上載者:User

標籤:leetcode   位元運算   二進位   

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.