Iterative solution for 15.4 (java)

#1

If we think reversely from the solution given by the book, we start with empty set, and iteratively add one element to it by cloning the current result set and adding the element to each of the set that was cloned. Each iteration generates exactly N more sets, where N = size of the previous result set. This leads to an iterative solution that is in my opinion much easier to read than the recursive one -

public static List<List<Integer>> generatePowerSet3(List<Integer> inputSet) {
    List<List<Integer>> powerSet = new ArrayList<>();
    powerSet.add(new ArrayList<>());

    for (int i = 0; i < inputSet.size(); i++) {
        int size = powerSet.size();
        for (int j = 0; j < size; j++) {
            List<Integer> currentSet = powerSet.get(j);
            List<Integer> newSet = new ArrayList<>(currentSet);
            newSet.add(inputSet.get(i));
            powerSet.add(newSet);
        }
    }

    return powerSet;
}

The result for count=3 reflects the process of the code -

<EmptySet>
0 
1 
0 1 
2 
0 2 
1 2 
0 1 2
0 Likes

#2

Hi @ray,

Many thanks for this solution, and it really is a good iterative one other than what we had in book which tries to enumerate from 0 to 2^n - 1.

0 Likes