Input a set and output all subsets of the set.

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.