Hiển thị tất cả tập con phân biệt của tập cho trước. Tập {1,2,3} → tập con: {}, {1}, {2}, {3}, {1,2}, {2,3}, {1,3}, {1,2,3}. Tập phần (power set) có 2^n phần tử.
Duyệt từ 0 đến 2^n-1, mỗi lần kiểm tra bit i của counter có set không, nếu có thì in phần tử thứ i.
Ví dụ mã nguồn
#include <iostream>
#include <cmath>
using namespace std;
void showPowerSet(char *set, int set_length) {
unsigned int size = pow(2, set_length);
for (int counter = 0; counter < size; counter++) {
cout << "{";
for (int j = 0; j < set_length; j++) {
if (counter & (1 << j))
cout << set[j] << " ";
}
cout << "}" << endl;
}
}
int main() {
char set[] = {'a', 'b', 'c'};
showPowerSet(set, 3);
}
Kết quả đầu ra
{}
{a }
{b }
{a b }
{c }
{a c }
{b c }
{a b c }