#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int nums[] = {1,2,3};
// nums元素的个数
int size = sizeof(nums) / sizeof(nums[0]);
// 子集个数
int row = 1 << size;
// 子序列
int childNums[size * sizeof(int)];
int col = 0;
// 记录每个子集元素个数
int colSize[row*sizeof(int)];
memset(childNums,0,size * sizeof(int));
// 申请堆空间,存放每个子集的首元素地址
int **allStr = (int **)calloc(row,sizeof(int *));
if(allStr == NULL)
{
perror("calloc failed: ");
return -1;
}
for(int i = 0; i < row; i++)
{
col = 0;
for(int j = 0; j < size; j++)
{
// 对i的每一位尝试构成子集
if(i & (1 << j))
{
// 如果i的第j位的二进制位为真,则nums[j]元素入子集
childNums[col++] = nums[j];
}
}
// 申请空间用于存放子集
int *temp = (int *)calloc(col,sizeof(int));
memcpy(temp, childNums, col*sizeof(int));
// 将temp挂在allStr的某一个元素
allStr[i] = temp;
// 记录每个子集的元素个数
colSize[i] = col;
}
// 遍历集合
for(int i = 0; i < row; i++) // 遍历allStr
{
for(int j = 0; j < colSize[i]; j++)
{
printf("%d\t",allStr[i][j]);
}
printf("\n");
}
return 0;
}