Duyệt tập con
  1. Cách đệ quy:
C++
#include<bits/stdc++.h>
using namespace std;

vector<int> v;
int n;

void dequy(int i) {
    if (i == n + 1) {
        // tinh toan
        for (int i: v) {
            cout << i << " ";
        }
        cout << endl;
        return;
    }

    v.push_back(i);
    dequy(i + 1);
    v.pop_back();
    dequy(i + 1);
}

int main() {
    // freopen("input.txt","r",stdin);
    ios::sync_with_stdio(0);
    cin.tie(NULL);

    n = 4;
    dequy(1);

    return 0;
}
  1. Cách bitmask
C++
#include<bits/stdc++.h>
using namespace std;

bool onBit(int bit, int i) {
    int x = bit & (1 << i);
    if (x == 0) return false; // bit thu i tat
    return true;
}

int main() {
    // freopen("input.txt","r",stdin);
    ios::sync_with_stdio(0);
    cin.tie(NULL);

    int n = 4;
    for (int bit = 0; bit < (1 << n); bit++) {
        vector<int> v;
        for (int i = 0; i < n; i++) {
            if (onBit(bit, i)) {
                v.push_back(i);
            }
        }

        // tinh toan
        for (int i: v) {
            cout << i << " ";
        }
        cout << endl;
    }

    return 0;
}

Bình luận

Mới nhất
Tải bình luận...

Không có bình luận nào.