Backtracking
Перебор с возвратом
A search technique that builds a solution one choice at a time. When a choice leads nowhere or all its possibilities have been explored, the algorithm undoes it and tries another.
Also known as: бэктрекинг
What backtracking does
Think of filling in a Sudoku grid. You try a digit in an empty cell and move on to the next cell. If you eventually reach a cell with no legal digit, you undo a choice and try a different digit. You don't have to start over: the earlier choices are still in place. The same approach can find the first solution, enumerate every solution, or report that none exists.
How the search works
Picture a tree whose nodes are partial solutions. The root is an empty solution, and each edge adds a choice. Backtracking usually explores this implicit tree depth-first: make a choice, explore what follows from it, and restore the previous state before trying the next option. Recursion is a convenient way to remember where to return, but an explicit stack also works.
If a partial solution cannot be extended into a valid answer, you can skip its entire subtree. This is called pruning. For example, a Sudoku row with two copies of the same digit can't be fixed by filling more cells. DFS describes the order of exploration; backtracking describes how the search tries and discards choices as it moves through that tree.
Example: choosing combinations
Suppose you want every way to choose k distinct numbers from 1 through n, with 0 <= k <= n. Each next number must be larger than the last, so [1, 3] and [3, 1] aren't counted separately. You can also skip any choice that leaves too few numbers to finish the combination.
def combinations(n, k):
results, path = [], []
def search(start):
needed = k - len(path)
if needed == 0:
results.append(path.copy())
return
for x in range(start, n - needed + 2):
path.append(x)
search(x + 1)
path.pop()
search(1)
return results
For n = 4 and k = 3, the first choice can be 1 or 2. Starting with 3 would leave only 4, not enough to complete the combination. The pop() restores path after each attempt. Copying path at the base case keeps that result from changing as the search continues.
Where it shows up in interviews
Common problems include generating permutations, solving N-Queens, and finding a word along a path through a grid. Before you code, explain what one search state contains, what counts as a complete answer, and which choices you can safely rule out. Then trace a small example to show both the forward step and the undo step. In a grid search, for instance, a cell marked as used on one path may need to be available again on a different path.
When discussing complexity, count the states you visit and the work done at each state, including copying results. Pruning can save substantial work, but it doesn't guarantee polynomial time. Separate working memory from output space: the combination example uses O(k) working space, but storing all the answers takes O(k * C(n, k)) space for k >= 1, where C(n, k) is the number of combinations.