N个元素的集合的所有子集个数为2N个。
public ArrayList<ArrayList<Integer>> getSubsets(ArrayList<Integer> set, int index){
ArrayList<ArrayList<Integer>> allsubsets;
if(index==0){//终止,加空集合
allsubsets = new ArrayList<arrayList<Integer>>();
allsubsets.add(new ArrayList<Integer>());//加个空集合
}
else{
allsubsets = getSubsets(set,index-1);
int item = set.get(index);
ArrayList<ArrayList<Integer>> moresubsets = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> subset : allsubsets){
ArrayList<Integer> newsubset = new ArrayList<Integer>();
newsubset.addAll(subset);
newsubset.add(intem);
moresubsets.add(newsubset);
}
allsubsets.addAll(moresubsets);
}
return allsubsets;
}
时间: 2024-10-10 13:01:35