Input a set and output all subsets of the set.
There is a pen question in the interview, which roughly means:
Input a set and output all subsets of the set. For example, input 1, 2, and 4 are as follows:
[1]
[2]
[4]
[1, 2]
[1, 4]
[2, 4]
[1, 2, 4]
The main research is the displacement operation and logic thinking ability. The specific code is as follows (it is absolutely reliable after being certified by the Local Machine ):
1 import java. util. arrayList; 2 import java. util. statement; 3 import org. apache. commons. collections. collectionUtils; 4 5/** 6 * enter a set, output all subsets of this set 7 * @ author liangyongxing 8 * @ time 2017-02-06 9 */10 public class SubListExport {11 public static void main (String [] args) {12 ArrayList <Integer> list = new ArrayList <Integer> (); 13 System. out. println ("enter a String of integers and separate them with commas:"); 14 String inputString = new SC Anner (System. in). next (). toString (); 15 if (inputString! = Null &&! InputString. isEmpty () {16 String [] strArray = inputString. split (","); 17 for (String str: strArray) {18 list. add (Integer. parseInt (str); 19} 20 ArrayList <Integer> allsubsets = getSubsets2 (list); 21 for (ArrayList <Integer> subList: allsubsets) {22 System. out. println (subList); 23} 24} 25} 26 27 public static ArrayList <Integer> getSubsets2 (ArrayList <Integer> subList) {28 ArrayList <Integer> allsubsets = new ArrayList <Integer> (); 29 int max = 1 <subList. size (); 30 for (int I = 0; I <max; I ++) {31 int index = 0; 32 int k = I; 33 ArrayList <Integer> s = new ArrayList <Integer> (); 34 while (k> 0) {35 if (k & 1)> 0) {36 s. add (subList. get (index); 37} 38 k >>= 1; 39 index ++; 40} 41 if (CollectionUtils. isNotEmpty (s) {42 allsubsets. add (s); 43} 44} 45 return allsubsets; 46} 47}