Backtracking
Backtracking solves a problem with exhaustive search: from an initial state it tries the possible solutions and keeps each one that meets the conditions. It stops when it finds what it needs or when it has tried everything. It almost always goes depth first, like a tree's preorder: it goes down one branch to the bottom before trying another. Example: finding every node with value 7 in a tree by walking it in preorder.
The name comes from how it works: it tries an option and, if it reaches a state it cannot continue from, it goes back. Going back is not just leaving a function: the state must also be left as it was. If the path is kept in a list path, trying adds the node and, before going back, it is removed. Trying and undoing are inverse operations, like a step forward and a step back.
Backtracking problems share a template. There is a state (state), what has been chosen so far, and some options (choices). First you check whether the state is a solution and, if so, you save it. Then, for each option: if it is valid, you choose it, go on with backtrack and undo it. For each problem only what the state is, what the options are and what is valid change.
There are 6 words that keep coming back in backtracking. Solution: an answer that meets the conditions. Constraint: a condition that limits which solutions count. State: where the search is, with what has been chosen. Attempt: choosing an option and updating the state. Backtrack: undoing the choice. Pruning: skipping paths that cannot work.
Backtracking finds every solution, but it can be very expensive: in the worst case it explores every possibility, and its time can be exponential or factorial. It also uses memory to keep the state at each level of the recursion. Even so, it is the best option when you cannot know in advance which choice works. To speed it up you use pruning or heuristic search, which tries the most promising paths first.
