b146簡單

87 第四區(臺中)資訊學科能力競賽(1998)|所有子集合

第i個元素對應遮罩的第i位,遮罩從0開始遞增。

解題思路

第i個元素對應遮罩的第i位,遮罩從0開始遞增。

對每個遮罩列出所有為1的位元對應元素,依原輸入順序輸出。

每個子集合都有唯一的選取位元串,故恰好輸出2^N個集合。C++以位元陣列實作二進位加一,避免固定位寬限制。

時間 O(N·2^N)加輸出字元量,空間 O(N)加元素字串;輸出本身即為指數規模。

Step-by-step animation

教學小例:以二進位計數枚舉全部子集合

回報動畫錯誤
步驟 1 / 3

兩元素x,y

遮罩00輸出0

遮罩00輸出0
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<string> a(n);
    for (auto &s : a)
        cin >> s;
    vector<int> b(n);
    while (true) {
        int c = accumulate(b.begin(), b.end(), 0);
        cout << c;
        for (int i = 0; i < n; i++)
            if (b[i])
                cout << ' ' << a[i];
        cout << '\n';
        int j = 0;
        while (j < n && b[j])
            b[j++] = 0;
        if (j == n)
            break;
        b[j] = 1;
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多