您的位置:首页 > 其它

List All Of The Subsets

2013-01-03 20:30 211 查看
Problem description:Please list all of the subsets of a known set including the empty set.

My idea: one thinking of the algorithm backtracking is to generate a tree of subset and the condition of an element in the super set for a subset is either on or off.Hence we can specialize the subset tree to a binary tree and we print once when we reach the bottom of the tree each time.It is also easy to write a program.

#include <stdio.h>
#define MAX 1000

int n=3;  //the number of the set elements
int set[MAX]={1,2,3};
int count=0;//the number of the subset.

void DFS(int level);
void print_set();

int main()
{
DFS(0);
return 0;
}

void DFS(int level)
{
if(level==n)
{
print_set();
return ;
}
int save=set[level];
set[level]=0;
int index=0;
for(index=0;index<2;index++)
{
DFS(level+1);
set[level]=save;
}

}

void print_set()
{
int index;
count++;
printf("%d: {",count);
for(index=0;index<n;index++)
{
if(set[index]!=0)
printf("%d ",set[index]);
}
printf("}\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: