Recursion and backtracking: Subsets
Backtracking builds answers one choice at a time. Make a choice, recurse to make the rest, then undo the choice and try the next one. It is how you list subsets, permutations, and combinations, and how you solve puzzles like sudoku.
The shape is always the same:
def walk(i: int) -> None:
if i == len(items):
result.append(chosen.copy()) # a copy, not the list itself
return
walk(i + 1) # skip items[i]
chosen.append(items[i])
walk(i + 1) # take items[i]
chosen.pop() # undo
The signal: "all", "every", or "list the possible". The output itself is exponential: n items have 2ⁿ subsets and n! orders, so no speed trick exists. Say that in an interview.
A common mistake: appending chosen instead of chosen.copy(). Every
answer then points at the same list, which ends up empty.
Exercise: finish subsets so it returns every subset of items. Keep
each subset in the same order as items. The order of the subsets does not
matter. Press Check to run the tests.