Backtracking
Explore choices and undo their effects.
Backtracking enumerates valid choice paths by making one decision, exploring its continuations, and restoring exactly the state that decision owned. Canonical choices remove symmetric duplicate paths without deleting required multiplicity.
Mechanism and state
For subsets of distinct values, a path contains increasing input indices. Emit a copy of the path at entry, then choose each later index, recurse with i+1, and remove exactly that choice before its next sibling. The empty initial path emits the empty subset. The algorithm enumerates output; it is not a polynomial shortcut around exponential output size. In board-word search, a choice also owns a coordinate: mark on frame entry, explore matching orthogonal trie edges, and unmark on pop. Consuming a found-word terminal is a separate call-wide deduplication action, not the path choice that is undone. A subset frame owns a start frontier; a permutation owns used occurrence indices; reusable combinations keep the chosen index while reducing a positive remaining sum; single-use combinations advance past it. N-Queens owns a column and two diagonal slots per placed queen. Word Search owns active coordinates and a suspended direction cursor. Emit independent snapshots only at the problem’s valid completion condition, which can differ from the recursive return condition.
Why the pattern works
Every subset has one unique increasing index sequence, so it corresponds to one recursion path. Advancing the starting index prevents reuse and duplicate permutations. Undo restores the parent’s state; output copies isolate earlier results from later mutations. Recursion depth is bounded by n. For board paths, the used set must equal exactly the coordinates of the live stack. Releasing a popped coordinate restores it for a sibling search; keeping dictionary descendants after reporting a prefix preserves longer words. Prove sound partial states, completeness of surviving choices, uniqueness of canonical value outputs, and termination separately. Equal siblings can be skipped after sorting a private copy, but deeper equal choices may still be required. For duplicate permutations consume equal occurrences in sorted-index order by requiring an earlier equal copy to be used first. Each undo releases only the current choice’s ownership; output snapshots survive restoration. Termination follows from increasing indices, fewer unused occurrences, a decreasing positive remainder, bounded path coordinates, or increasing queen row, depending on the problem.
Work through an example
For [1,2], entry emits []; choose 1 emits [1]; choose 2 emits [1,2]; undo 2 and 1; choose 2 at root emits [2]. All four results must remain independent lists after traversal ends. On [1,1,2], duplicate subsets skip a second equal root sibling while still allowing [1,1]. Duplicate permutations permit the second 1 once its first copy is used, giving [1,1,2], [1,2,1], [2,1,1]. In reusable combination sum, choosing 2 for target 6 keeps index 2 available and lowers remaining to 4; single-use search advances after that occurrence. In Word Search a matched path is shown before explicit cleanup releases its private marks. In four-queen search, columns and both diagonal families prune an attacking choice before another row is entered.
Where the reasoning fails
Adding the working list itself to output aliases stored results. Skipping duplicate values at every depth is not the same as skipping equal siblings when input duplicates are allowed. Always include output copying in complexity. A globally visited board cell can suppress later legal paths. In-place marker writes can also corrupt aliased source rows; an independent coordinate matrix preserves the input contract. A global visited set is unsuitable for path-local word search. Sorting caller input, storing the working list directly, skipping all equal values, or confusing i with i+1 changes the contract. Nonpositive reusable candidates invalidate the decreasing-sum proof. Row/column index arithmetic needs an empty-board convention. Enumeration complexity must include output copying and, for queen boards, every emitted character; pruning cannot make factorial or exponential output polynomial.
Reconstruct the reasoning
For n values, derive both the number of subsets and the total number of element entries across them. Explain what memory changes with a lazy iterator. Compare removing a subset choice with releasing a board coordinate, and explain why a reported trie terminal is not restored during the same board call. For DSA-119–DSA-125, name the owned resource, emission condition, progress measure, duplicate policy, undo operation, input/output mutation promise and independent oracle. Trace a chosen path before child entry, after child return and after undo. Compare subset masks, factoradic ranks, amount-layer set DP, coordinate-mask reachability and exhaustive column assignments as alternative verification methods. Explain why a sorted occurrence index can repeat in DSA-122 but not DSA-123, and why diagonal flags are safe to clear only after proving exclusive ownership.
Apply this foundation
- Word Search II · Explanation
- Subsets · Explanation
- Subsets II — Duplicates · Explanation
- Permutations · Explanation
- Permutations II — Duplicates · Explanation
- Combination Sum — Reusable Candidates · Explanation
- Combination Sum II — Each Candidate Once · Explanation
- Word Search — Single Word · Explanation
- N-Queens · Explanation