List All Of The Subset In Another Method

简介:
Problem description:Please list all of the subsets of a known set including the empty set.

Thinking: the subset's sum of a super set is (n is the number of the super set element) while a n-bit binary space could express  numbers too.So our target is to generate all of the binary numbers in n bit space.Before solving the problem,please look at this point:

11111 01111
+                 1
-------------------
11111 10000

When the number add 1,the current bit will become to 0 and generate a carry if it was 1.Next,the previous bit 1 will become 0 with a carry,too.If its current bit is 0 ,it becomes 1 without a carry and stop the addition.Hence,the program process is clear.
 1 #include <stdio.h>
 2 #include <math.h>
 3 #define MAX 1000
 4 
 5 int n=4;// the number of the set elements
 6 int set[MAX]={1,2,3,4};
 7 int path[MAX]={0};
 8 int count=1;
 9 
10 //prototype
11 void print_set();
12 
13 int main()
14 {
15     int sum=(int)pow(2.0,n)-1;
16     int index,index_re;
17     printf("%d:{}\n",count);
18     for(index=0;index<sum;index++)
19     {
20         for(index_re=n-1;index_re>=0;index_re--) 
21         {
22             if(path[index_re]==1) 
23                 path[index_re]=0;
24             else
25             {
26                 path[index_re]=1;
27                 break;
28             }
29         }
30         count++;
31         printf("%d:{",count);
32         print_set();
33     }
34     return 0;
35 }
36 
37 void print_set()
38 {
39     int index;
40     for(index=0;index<n;index++)
41     {
42         if(path[index]!=0) 
43             printf("%d ",set[index]);
44     }
45     printf("}\n");
46 }
Reference material: C语言名题精选百则技巧篇 in Chinese.

本文转自NeilHappy 51CTO博客,原文链接:http://blog.51cto.com/neilhappy/1107818,如需转载请自行联系原作者
相关文章
|
6月前
|
SQL JSON Java
Java【问题记录 02】对象封装+固定排序+list All elements are null引起的异常处理+Missing artifact com.sun:tools:jar:1.8.0
Java【问题记录 02】对象封装+固定排序+list All elements are null引起的异常处理+Missing artifact com.sun:tools:jar:1.8.0
77 0
成功解决ValueError: ‘usecols‘ must either be list-like of all strings, all unicode, all integers or a ca
成功解决ValueError: ‘usecols‘ must either be list-like of all strings, all unicode, all integers or a ca
为什么有的备份归档日志用list backup of archivelog all查不到,但在第三方备份软件中可以查到
提问:为什么有的备份归档日志用list backup of archivelog all查不到,但在第三方备份软件中可以查到?
|
IDE 开发工具 图形学
|
存储 缓存
memcached实战系列(五)Memcached: List all keys 查询所有的key
memcached可能当时设计的时候就把它定位为内存性的kv结构的缓存系统。所以没有持久化到磁盘的命令,也没有查看所有key的值得命令。可能觉得没必要吧,你要是缓存1个G内存的数据,自己都头大,还敢看。
1126 0
|
5月前
|
安全 Java
java线程之List集合并发安全问题及解决方案
java线程之List集合并发安全问题及解决方案
953 1