Problem Description: Given a collection, enumerate all the non-empty-empty sets of this Union.
For example: {a,b,c}, non-empty set: {A}{B}{C}{AB}{AC}{BC}{ABC}
The coding algorithm here is to encode each one, 0 means that the corresponding element does not appear, and 1 indicates that the corresponding element appears.
So the code for ABC corresponds to
0.000 {}
1.001 {C}
2.010 {B}
3.011 {BC}
4. {A}
5.101 {AC}
6. {AB}
7.111 {ABC}
There are two ways to
The first method fun1 the corresponding bits manually, this method is more general, it is recommended that you master this method.
The second method, Fun2, is to use a Java-brought package that converts the specified integer to a binary form.
The Java code is as follows:
1 Public classQJZJH {2 Public Static voidfun1 (String str) {3 for(intI=1;i<math.pow (2,str.length ()); i++)4{intA=i;5String ziji= "";6 for(intJ=str.length () -1;j>=0;j--)7 {8 if((a%2)!=0) Ziji=str.charat (j) +ziji;//using decimal conversion to binary algorithm, the last few binary9A=a/2;Ten } OneSystem.out.println (i+ "" +Ziji); A } - } - the Public Static voidfun2 (String str) { - for(intI=1;i<math.pow (2,str.length ()); i++) - { -String ziji= ""; +String binary=integer.tobinarystring (i);//convert an integer to 2 in the form of a Java-based method, with the highest post converted to 1 - for(intJ=binary.length () -1;j>=0;j--) + { A if(Binary.charat (j)! = ' 0 ') Ziji=str.charat (J+str.length ()-binary.length ()) +Ziji; at - } -System.out.println (i+ "" +Ziji); - } - } - Public Static voidMain (string[] args) { in //TODO Auto-generated method stubs -String str= "ABC"; to fun1 (str); + System.out.println (); - fun2 (str); the } *}
View Code
The output is:
1 C
1 A
3 BC
3 F
5 AC
6 AB
7 ABC
1 C
1 A
3 BC
3 F
5 AC
6 AB
7 ABC
Poor lifting sub-collection