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);
}
}
}
输入一个集合,输出这个集合的所有子集
最新推荐文章于 2020-02-19 17:18:21 发布