List every subset of a set of distinct numbers, empty one included. For each number, branch on taking it or leaving it.
▼The problem
Given a list of distinct numbers, return every possible subset (the power set), including the empty one.
Example: [1, 2, 3] → 8 subsets.
def subsets(nums):
out = []
def go(i, picks):
if i == len(nums):
out.append(picks[:]) # save a copy
return
picks.append(nums[i]) # take it
go(i + 1, picks)
picks.pop() # backtrack
go(i + 1, picks) # leave it
go(0, [])
return outTRY IT ON LEETCODE ▶The solution
def subsets(nums):
out = []
def go(i, picks):
if i == len(nums):
out.append(picks[:]) # save a copy
return
picks.append(nums[i]) # take it
go(i + 1, picks)
picks.pop() # backtrack
go(i + 1, picks) # leave it
go(0, [])
return outTranscript
Subsets. Given a list of distinct numbers, return every possible subset: every way to pick some of them, from none at all to all of them. The empty one counts too.
Take one, two, three. There are eight subsets: empty; one; two; three; one two; one three; two three; and one two three.
Why eight? Each number is either in a subset or out. Three numbers, two choices each: two times two times two is eight. A fourth number doubles it to sixteen. So no trick can beat this: the answer itself has two to the n lists.
Recursion turns that choice into a plan. Look at the first number and decide: take it, or leave it. Then ask the same question about the rest of the list. When no numbers are left, the choices you made form one subset.
Draw every choice as a tree. At the top, nothing is chosen. Branch on one: take it or leave it. Each branch splits again on two, then on three. Three levels of yes or no give eight leaves, one for every subset.
In code, a helper takes a position and the current picks. If the position is past the end, save a copy, because the picks keep changing. Otherwise, add the number and recurse, then remove it and recurse again without it. That remove step is the backtrack: it undoes the choice, so the other branch starts clean.
Let's follow the paths. Take one, take two, take three: save one two three. Back up, leave three: one two. Back up twice, leave two, take three: one three. Leave three: just one. Then the same again without one: two three, two, three, and last, the path that leaves everything: the empty set. Eight saved.
There are two to the n subsets, each up to n long, so the time is n times two to the n. Apart from the output, the space is just the picks and the recursion, which is only n deep.
Take it or leave it, all the way down. That's Subsets.