Skip to content

Subsets

Lesson 2 of 5 · 5 min

Subsets

Step 1 of 7

A subset is one yes-or-no answer per item, so every level of the tree has exactly two branches.

The Idea

A subset is one yes-or-no answer per item, so the decision tree is binary: skip nums[i], or take it and move on.

The index only ever moves forward, which is what stops {1, 2} and {2, 1} both appearing. Every leaf is a complete set of decisions, so there are exactly two to the power n of them — and the pop after the take branch is again what keeps the shared path honest.

Real-World Example

Choosing which optional modules to switch on for a build. Each flag is independent, and the release team wants every combination tested — eight builds for three flags, sixteen for four.

The Code

Your turn

What does this print?

out = []
subsets([1, 2, 3], 0, [], out)
print(len(out))

Mini quiz

1 / 3

How many leaves does the subset tree have for n items?