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");
- }
阅读(1368) | 评论(0) | 转发(0) |