ที่นี่เราจะมาดูวิธีการแสดงชุดย่อยที่แตกต่างกันทั้งหมดของชุดที่กำหนด ดังนั้น หากเซตเป็น {1, 2, 3} เซตย่อยจะเป็น {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3} , {1, 2, 3}. ชุดของชุดย่อยทั้งหมดเรียกว่าชุดกำลัง ชุดพลังมีองค์ประกอบ 2n
เราจะวนซ้ำผ่าน 0 ถึง 2n (ไม่รวม) ในการวนซ้ำแต่ละครั้ง เราจะตรวจสอบว่ามีการตั้งค่าบิต ith ในตัวนับปัจจุบันหรือไม่ จากนั้นพิมพ์องค์ประกอบ ith
ตัวอย่าง
#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 < size; j++) {
if(counter & (1<<j))
cout << set[j] << " ";
}
cout << "}" << endl;
}
}
int main() {
char set[] = {'a','b','c'};
showPowerSet(set, 3);
} ผลลัพธ์
{}
{a }
{b }
{a b }
{c }
{a c }
{b c }
{a b c }