Builds onRecursion and the call stack
01The idea
Backtracking builds every solution one choice at a time. At each step you try each possible choice, go deeper with it, and then undo it to try the next one. The choices form a tree. The root is the empty start, each branch is one choice, and each leaf is a full answer or a dead end.
Every backtracking function has the same shape:
- If the current state is complete, record a copy of it and return.
- For each choice you can make here:
- skip the choice if it breaks a rule, which is called pruning
- make the choice, by adding it to the state
- call the function again to fill in the rest
- undo the choice, by removing it from the state
The undo is what makes it backtracking. One shared list, path, holds the current choices. After each recursive call returns, the list must look exactly as it did before the choice, so the next choice starts from the same place.
Pruning keeps the tree small. If a partial answer already breaks a rule, no longer answer that starts with it can be valid. Cut the branch there, and you skip every leaf under it.
02How to spot it
Use backtracking when the problem asks for:
- all subsets, all combinations, all permutations or all arrangements
- every string or path that follows some rules
- placing items on a board so they do not clash, such as queens on a chessboard
- any answer to a puzzle, such as a Sudoku, where you must try choices and back out of dead ends
The input is small, such as n up to 10 or 20, because the number of answers can double with each choice. Seeing "return all" together with a small limit is a strong sign.
If the problem asks only how many answers there are, or for the best one, check first whether dynamic programming can count them without listing them.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue