无重复元素集合的子集,比如{1,2,3}的子集
解题思路:n个元素总共有2^n种情况,运用位运算模拟,例如三个数字可以用三bit表示,1代表存在该数字,0代表不存在
#include <iostream>
using namespace std;
typedef unsigned long DWORD; // DWORD 即double world,双字节。
void print_allSubSet(int arr[], int n)
{
DWORD i, j, total, mask;
total = (1 << n);
for (j = 0; j < total; j++) // 每循环一次选出一个子集
{
i = 0; // 每一次循环,i都重新置0;对应原数组中的第一个数字。
mask = j; // 序号j对应的是第(j+1)个子集。
while (mask > 0) // 通过移位的方式,直至mask的二进制形式中,所有位都为0。
{
if (mask & 1) // 若mask的二进制形式的最后一位非0,输出该位对应的数字。
cout << arr[i] << " " ;
mask >>= 1; // mask右移一位
i++;
}
cout << endl;
}
}
int main(int argc, const char * argv[]) {
int n = 3; //求3个元素的所有子集。
int arr[3];
int i;
for (i = 0; i<n; i++)
arr[i] = i + 1; //arr表示一个集合,共有n个元素
print_allSubSet(arr, n);
return 0;
}