Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

組合演算法 C++ 高效實作:二進位輔助法

1. 什麼是組合

與排列不同,組合不考慮取出的順序。從 m 個元素中取 n 個,組合總數為 C(m, n)。以 1,2,3,4,5 中取 2 個為例,共 10 種:

1,2  1,3  1,4  1,5
2,3  2,4  2,5
3,4  3,5
4,5

2. 用二進位思維高效枚舉

遞迴雖然直觀,但效率較低且不易讀懂。這裡介紹一種以二進位為核心的做法。先回想排列的高效解法:把 1,2,3 的全排列,換算成「由 1、2、3 組成、從小到大排列的所有三位數」:

123 < 132 < 213 < 231 < 312 < 321

組合可以用完全類似的思路。用一個 5 位元的二進位數表示某種取法(1 代表選中,0 代表不選),讓它遍歷所有可能(0~31),只保留「恰好有兩個 1」的情形。若把二進位由左往右當權重換算成十進位,你會發現產生的順序正好由小到大:

1,2  (1,1,0,0,0) → 3
1,3  (1,0,1,0,0) → 5
2,3  (0,1,1,0,0) → 6
1,4  (1,0,0,1,0) → 9
2,4  (0,1,0,1,0) → 10
3,4  (0,0,1,1,0) → 12
1,5  (1,0,0,0,1) → 17
2,5  (0,1,0,0,1) → 18
3,5  (0,0,1,0,1) → 20
4,5  (0,0,0,1,1) → 24

策略三步驟:

1. m 取 n:初始化 m 個 0,把前 n 個改成 1,即最小的二進位;
2. 找下一個較大的數:因為二進位是由左往右,遇到「1,0」時改成「0,1」數值就變大了;
3. 但 (0,1,1,0,0)→6 之後,若只把 1,0 換成 0,1 會得到 (0,1,0,1,0)→10,而真正比 6 大的下一個是 (1,0,0,1,0)→9。所以交換之後,還要把該位置之前所有的 1 全部移到最前面,才是最小的下一個值。

3. 程式碼

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void printResult(vector<int>& vecInt, int t[])
{
    for (int i = 0; i < vecInt.size(); ++i) {
        if (vecInt[i] == 1) {
            cout << t[i] << " ";
        }
    }
    cout << endl;
}

bool compare(int a, int b)
{
    return a > b;      // 降序,把 1 往左排
}

void combination(int t[], int c, int total)
{
    // 初始組合:1,1,0,0,0
    vector<int> vecInt(total, 0);
    for (int i = 0; i < c; ++i) {
        vecInt[i] = 1;
    }
    printResult(vecInt, t);

    for (int i = 0; i < total - 1; ++i) {
        if (vecInt[i] == 1 && vecInt[i + 1] == 0) {
            swap(vecInt[i], vecInt[i + 1]);              // 1. 1,0 → 0,1
            sort(vecInt.begin(), vecInt.begin() + i, compare);  // 2. 前面的 1 移到最左
            printResult(vecInt, t);
            i = -1;                                      // 從頭重新掃
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int N = 5;
    int t[N] = {1, 2, 3, 4, 5};
    combination(t, 2, N);
    system("pause");
    return 0;
}

4. 如何求「所有」組合

理解了上面的思路,求全部組合反而更簡單:用一個 n 位元的二進位數表示結果,剛好遍歷 0 ~ 2ⁿ−1:

{}     000
1      001
2      010
1,2    011
3      100
2,3    110
1,2,3  111
#include <iostream>
using namespace std;

void printEachResult(int t[], int index, int total)
{
    for (int i = 0; i < total; ++i) {
        if ((index >> i) & 1 == 1) {     // 實務上建議寫成 ((index >> i) & 1) == 1
            cout << t[i] << " ";
        }
    }
    cout << endl;
}

void combination(int t[], int count)
{
    for (int i = 0; i < (1 << count); ++i) {
        printEachResult(t, i, count);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int N = 3;
    int t[N] = {1, 2, 3};
    combination(t, N);
    system("pause");
    return 0;
}

這裡的位元技巧值得記住:1 << count 就是 2 的 count 次方,(index >> i) & 1 則是取出第 i 個位元。要注意運算子優先級——& 低於 ==,所以原寫法 (index>>i)&1 == 1 實際上會先算 1 == 1,加上括號才是正確行為。

若 m 很大,這種做法會受 2^m 的指數爆炸限制,此時應改用遞迴或 Gosper's hack(在固定位元數的整數上直接求下一個「同 popcount」的數),後者能免去掃描整組位元的成本。

Copyright © Linux教程網 All Rights Reserved