Power set
The power set of n items has 2^n subsets, one for every number from 0 to 2^n - 1. Read the bits of each number to decide which items it includes. This gives every subset without recursion.
How to recognise it
- The question asks for all subsets and n is small (about 20 or less).
- An iterative method is preferred over recursion.
The idea in one picture
Count in binary from 000 to 111. Each count is a row of yes/no answers for the three items, and every possible row
appears exactly once.
| mask | bits (c b a) | subset |
|---|---|---|
| 0 | 000 | [] |
| 1 | 001 | [a] |
| 2 | 010 | [b] |
| 3 | 011 | [a, b] |
| 4 | 100 | [c] |
| 5 | 101 | [a, c] |
| 6 | 110 | [b, c] |
| 7 | 111 | [a, b, c] |
Template
for mask from 0 to 2^n - 1:
subset = items i where bit i of mask is 1
record subset
Common mistakes
- Looping to
2^ninclusive, which adds an extra mask with bitnset. - Shifting a 32-bit
1byn ≥ 31. - Forgetting the empty subset.
Problems
- Power Set Using Bit Manipulationmediumguide ready