I'm trying to write code to output all subsets of a set (represented by a list of integers). Why doesn't the following code work?
public static List<List<Integer>> powerSet(List<Integer> l){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (l.size() == 0) {
result.add(new ArrayList<>());
}
else {
List<List<Integer>> prev = powerSet(l.subList(0, l.size() - 1));
for (List<Integer> x : prev) {
x.add(l.get(l.size() - 1));
result.add(x);
}
}
return result;
}
My thinking is that to compute the subsets of a set A[0...n-1] of size n, we can just add the last element A[n - 1] of the set to the subsets of A[0...n-2]. However, the code above only gives me the same set:
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(0);
l.add(1);
l.add(2);
List<List<Integer>> result = powerSet(l);
System.out.println(result.toString());
}