Problem
FAANG · LeetCode #78

Subsets — three-stage drill

1The ProblemMedium

Subsets

Return every possible subset (the power set) of a list of distinct integers.

every subset of[1, 2, 3]102132pick any combination — including none and all[ ][1][2][3][1,2][1,3][2,3][1,2,3]count2³ = 8
Examples
[1,2,3]→ [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]][0]→ [[], [0]]

constraintAll numbers are distinct; the answer may be returned in any order.

2The PatternTIME O(n · 2ⁿ) · SPACE O(n)

Backtracking

Build a candidate one choice at a time, exploring every branch of the decision tree. When a path is complete (or dead), un-choose the last step and try the next — a DFS that always cleans up after itself.

build a path one choice at a time; un-choose to try the nextpath∅results — the power set of [1, 2][][1][1, 2][2]record the current path → []
Problems using this pattern
3The SolutionRESULT → 8 subsets

Step through it

DFS over nums — choose · record · un-choosenums102132path∅↩ ANSWERsubsets found =1results[]record the empty subset → []
record the empty subset → []
Step 1 / 23
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent