/*
此解法通过不停的产生下一个集合来生成一个集合的所有子集
如要产生1~4的所有子集,如果当前集合是{1},下一个集合则是{1,2} ,{1,2,3},
{1,2,3,4} (set[position + 1] = set[position] + 1; position++)
下一个集合呢?即{1,2,4}(set[--position]++)
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
#define MAXSIZE 20
#define LOOP 1
int main()
{
int set[MAXSIZE];
int n, i;
int position;
char line[100];
cin >> n;
printf("\n{}");
//init
position = 0;
set[position] = 1;
while (LOOP) {
//output
printf("\n{%d", set[0]);
for (i = 1; i <= position; i++)
printf(",%d", set[i]);
printf("}");
if (set[position] < n) {
set[position+1] = set[position] + 1; //不是set[position++]= set[position]+1
position++;
}
else if (position != 0)
set[--position]++;
else
break;
}
}
产生一个集合的所有子集
最新推荐文章于 2020-01-17 15:16:32 发布