我有这个简单的程序来计算给定集合的所有子集。
我相信这个算法是正确的。但是部分:
while (included.size()>0){
ArrayList<Integer> temp =included.remove(0);
temp.add(first_element);
output.add(temp);
}
该语句temp.add(first_element)
不必要地更新 not_included。请帮我理解为什么。
public class Recursion {
public static ArrayList<ArrayList<Integer>> getSubsets (ArrayList<Integer> input_set){
ArrayList<ArrayList<Integer>> output=new ArrayList<ArrayList<Integer>>();
if (input_set.isEmpty()){
ArrayList<Integer> this_subset=new ArrayList<Integer>();
output.add(this_subset);
}
else if (input_set.size()==1){
ArrayList<Integer> empty_subset=new ArrayList<Integer>();
output.add(input_set);
output.add(empty_subset);
}
else{
int first_element=input_set.remove(0);
ArrayList<ArrayList<Integer>> included = getSubsets(input_set);
ArrayList<ArrayList<Integer>> not_included = getSubsets(input_set);
while (included.size()>0){
ArrayList<Integer> temp =included.remove(0);
temp.add(first_element);
output.add(temp);
}
while (not_included.size()>0){
output.add(not_included.remove(0));
}
}
return output;
}
public static void main(String[] args) {
ArrayList<Integer> test= new ArrayList<Integer> ();
test.add(2);
test.add(1);
System.out.print(getSubsets(test));
}
}