Pages

12/07/2021

[Java] Generate power set of set

A power set is the set of all possible subsets of a set. For example for {1,2} it is {{}, {1}, {2}, {1,2}}

It contains 2^N elements.

We can use DFS recursion to generate it, removing one element from each subset we generate at each step, skipping repeated sets.

This can be done in O(N) space (we won't add more than N calls on the stack) and O(N 2^N) time since there are 2^N sets to generate AND everytime we create a new set we need to copy over all its elements in a NEW set.

You can check my implementation of generatePowerSet on my Gist along with some tests in GeneratePowerSetJTests.

No comments:

Post a Comment

With great power comes great responsibility