A tree of choices
Goal: list every subset of [1, 2, 3]. Each number is one yes-or-no choice: take it (left edge) or skip it (right edge). Three choices make 2 × 2 × 2 = 8 leaves, one per subset. Each block shows the list chosen so far.
The code walks this tree by recursion. Each call is one block, and the rose puck marks the call running now. One shared list, path, holds the choices made so far. Going down an edge changes path; coming back up must undo it.
Choose, explore, un-choose
Line 5 chooses: path.append(1) puts 1 in path. Line 6 explores: one call further down. The same happens for 2 and 3. Now i equals len(nums), so every number is decided and line 3 saves a copy: [1, 2, 3] is found.
The leaf returns to the call for 3. Line 7 un-chooses: path.pop() removes 3, so path is [1, 2] again. Line 8 explores the skip branch with that same list and saves [1, 2]. Undoing each choice lets one list serve every branch.
Run it to the end. The puck goes depth first: the take edge, back up, then the skip edge. It saves 8 subsets, [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3], [], in 15 calls, with one three-cell list the whole time.
Each extra number doubles the leaves: n numbers give 2ⁿ subsets and 2ⁿ⁺¹ − 1 calls (15 here). Copying a leaf costs up to n steps, so the search is Θ(n·2ⁿ). For n = 20 that is 1,048,576 subsets.
Permutations
Now list every order of [1, 2, 3]. At each level, choose any number not yet in path. The root has 3 choices, then 2, then 1: 3 × 2 × 1 = 6 leaves. The pattern is the same: append, recurse, pop.
Line 5 tries each number; line 6 skips any already in path. Each choice is appended, explored, then popped so the next number can take its place. Found: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1], in 16 calls.
n numbers have n! orders: 3! = 6, but 10! = 3,628,800. Backtracking cannot shrink a list that long; it saves rebuilding path at every leaf. It shines when a rule can stop a branch early, the subject of N-queens and pruning.
What happens
;; step 1/9 · choices nums = [1, 2, 3] level 0: decide 1 level 1: decide 2 level 2: decide 3 left edge = take right edge = skip leaves: 2 × 2 × 2 = 8 [1, 2, 3] [1, 2] [1, 3] [1] [2, 3] [2] [3] []
Choose, explore, un-choose is the shape of every backtracking search: change the shared state, recurse, then put the state back exactly as it was. Stanford CS106B teaches it under that name; Sedgewick and Wayne call the last step "clean up". out.append(path.copy()) saves a copy. Writing out.append(path) would store the same list object 8 times, and since path ends empty, out would hold 8 empty lists.