1. 程式人生 > >輸入一個集合,輸出這個集合的所有子集

輸入一個集合,輸出這個集合的所有子集

package cn.edu.bupt.sherry;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
	/*
	 *  二級制 001 ——> index = 0 {list.get(0)}
	 */
	public static ArrayList<ArrayList<Integer>> getSubsets2(ArrayList<Integer> set){  
	    ArrayList<ArrayList<Integer>> allsubsets = new ArrayList<ArrayList<Integer>>();  
	    int max = 1 << set.size(); //how many sub sets  
	    for(int i=0; i<max; i++){  
	        int index = 0;  
	        int k = i;  
	        ArrayList<Integer> s = new ArrayList<Integer>();  
	        while(k > 0){  
	            if((k&1) > 0){  
	                s.add(set.get(index));  
	            }  
	            k>>=1;  
	            index++;  
	        }  
	        allsubsets.add(s);  
	    }  
	    return allsubsets;  
	} 
 
public static void main(String[] args){  
    ArrayList<Integer> s = new ArrayList<Integer>();  
    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入一串整數並在輸入時用英文逗號隔開:");
    String inputString=sc.next().toString();
    String stringArray[]=inputString.split(",");
    int num[]=new int[stringArray.length];
    for(int i=0;i<stringArray.length;i++){
     num[i]=Integer.parseInt(stringArray[i]);
     s.add(num[i]); }
     
    
    ArrayList<ArrayList<Integer>> allsubsets = getSubsets2(s);  
    for(ArrayList<Integer> set : allsubsets){  
        System.out.println(set);  
    }
    }
}