[][1][][1,2][][1][2][3][1,3][][1,2][1][2,3][2][1,2,3][][1][2][3][1,2][1,3][2,1][2,3][3,1][3,2][1,2,3][1,3,2][2,1,3][2,3,1][3,1,2][3,2,1]path[0]path[1]path[2]1def subsets(nums, i, path, out):2 if i == len(nums):3 out.append(path.copy())4 return5 path.append(nums[i]) # choose6 subsets(nums, i + 1, path, out) # take7 path.pop() # un-choose8 subsets(nums, i + 1, path, out) # skip1def perms(nums, path, out):2 if len(path) == len(nums):3 out.append(path.copy())4 return5 for x in nums:6 if x not in path:7 path.append(x) # choose8 perms(nums, path, out) # explore9 path.pop() # un-choosecallsfound
Blocks: one call each, labelled with path at that callEdges: one choice each; in the subset tree left takes the number, right skips itPuck: the running call · chip: a number going into or out of pathEvery block is one call of the recursive function and shows the list path when that call starts. The rose puck walks the tree depth first; a chip flies into path on each append and back out on each pop, so one three-cell list serves every branch. Subsets of [1, 2, 3]: 8 leaves, 15 calls. Permutations: 6 leaves, 16 calls.

A tree of choices

  1. 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.

Choose, explore, un-choose

Permutations

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.