The powerset of {1, 2, 3}
is:
{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}
Let\'s say I have a Set
in Java:<
We could write the power set with or without using recursion. Here is an attempt without recursion:
public List> getPowerSet(List set) {
List> powerSet = new ArrayList>();
int max = 1 << set.size();
for(int i=0; i < max; i++) {
List subSet = getSubSet(i, set);
powerSet.add(subSet);
}
return powerSet;
}
private List getSubSet(int p, List set) {
List subSet = new ArrayList();
int position = 0;
for(int i=p; i > 0; i >>= 1) {
if((i & 1) == 1) {
subSet.add(set.get(position));
}
position++;
}
return subSet;
}