Backtracking & Exact-Length Mixes
In short: backtracking tries choices systematically and abandons a
branch the moment it can't work. Every call does the same three things:
choose (add one option to the path), explore (recurse on everything
that follows), un-choose (undo the choice before trying the next one).
The path is one shared list that grows and shrinks as the search goes
deeper and comes back — never a formula, just disciplined trial and error.
Subsets cost O(n · 2ⁿ), permutations O(n · n!), and a continue that skips
a branch that can't work (pruning) cuts real work without changing that
worst case.
![Four snapshots of the path list: choose A, choose B, un-choose B back to [A], then choose C — one shared list growing and shrinking](/api/assets/dsa/assets/ea0b3e72a4e5341f.png)
Finding every two-track mix
Tunebox Radio has a 7-minute gap before the news, and the DJ wants every combination of tracks that fills it exactly, not just one. Start with the simplest shape — every subset of a list — choosing, recursing, then undoing:
path is one list shared by every call. start only offers tracks
after the last one chosen, so ["Blink", "Aurora"] never shows up as a
second copy of ["Aurora", "Blink"].
❓ Cross-question: "Why
path[:]and not justpath?"pathkeeps changing. Appendingpathitself stores a reference, so every entry inoutends up the same list — empty by the time the search finishes.path[:]stores a snapshot.
The mistake: recording the live list instead of a copy. Every "subset"
ends up pointing at the same emptied-out path:
This should print all four subsets of ["a", "b"]. It prints four empty lists. Make each recorded subset keep its contents.
Draw each call as a node and each loop step as an edge to a child — three tracks make exactly 2³ = 8 calls, one per subset:
Each call is one node and records one subset, so three tracks make 2³ = 8 calls.
explore(0) records the empty subset, then loops over A, B and C. 8 nodes, 7 edges, directed. At []. Settled: [].
def count_nodes(n, start=0):
return 1 + sum(count_nodes(n, i + 1) for i in range(start, n))
print(count_nodes(5))