Backtracking
medium 20 minBacktracking builds an answer one choice at a time and abandons a partial answer the moment it cannot work.
Chapter mnemonic
Backtracking in three moves
Lay a tile. Try the trail. Lift the tile.
What must you do after returning from exploring a branch?
Undo its choice so the next branch starts from the same state.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Try it, check it, undo it, move it.
A treasure hunter in a cave. At every fork she picks a tunnel and walks on, watching for traps (the constraints). When a tunnel ends in rock she walks back to the last fork and takes the next tunnel, until she finds the treasure or has tried them all.
Cheat sheet
- Rhythm
- choose, explore, unchoose
- Traversal
- DFS on a decision tree
- Time
- O(b^d) nodes
- Space
- O(d) path and stack
- Subsets
- 2ⁿ, O(n · 2ⁿ)
- Permutations
- n!, O(n · n!)
- N-Queens
- O(n!), 92 boards for n = 8
- Word Search
- O(R · C · 4^L)
- Save
- path[:], never path
Spot it when you see
- The problem says all, every or generate: all subsets, every arrangement, generate parentheses.
- Place items so that no two conflict: queens, Sudoku digits, timetable slots.
- Find a word or path in a grid without reusing cells.
- Partition a string or array so every part meets a rule.
- Small limits such as n ≤ 10 or n ≤ 20.
Tricks that stick
- BACKTRACK: Build incrementally, Abandon invalid paths, Check before recursing, Keep track of state, Try all options, Recurse deeper, Always restore, Collect at the base case, Know when to stop.
- Try it, check it, undo it, move it.
- Subsets look forward with a start index; permutations look everywhere with a used array.
- 2ⁿ for in-or-out, n! for arrange-them-all.
- Diagonals: r minus c going one way, r plus c going the other.
Do not forget
- Forgetting to undo the choice after the recursive call.
- Saving path instead of a copy of path.
- Saving an answer without returning from the base case.
- Checking constraints after choosing instead of before.
- Duplicate answers when the input has repeated values and you do not sort and skip.
- Marking grid cells and never restoring them.