Backtracking is exhaustive recursion with a decisive improvement: it abandons a branch as soon as it sees it cannot lead to a solution. It is like exploring a maze: if you reach a dead end, you go back to the last fork and try another path.
The outline
- Choose a possible option.
- Check whether it is still valid (if not, it is discarded: this is pruning).
- Explore the rest of the problem recursively.
- Undo the choice to try the next one.
def backtracking(state):
if is_complete(state):
save_solution(state)
return
for option in possible_options(state):
if is_valid(state, option): # pruning: only continue if valid
apply(state, option)
backtracking(state)
undo(state, option)
Example: subsets that add up to a target
Trying the 2ⁿ subsets and adding them up is the simplest way, but you can prune: if all the numbers are positive and the sum has already exceeded the target, it is useless to keep adding.
def search(values, i, remaining, current, solutions):
if remaining == 0: # solution: the sum is exact
solutions.append(list(current))
return
if i == len(values) or remaining < 0: # PRUNING: no elements left or we overshot
return
current.append(values[i]) # with the element
search(values, i + 1, remaining - values[i], current, solutions)
current.pop()
search(values, i + 1, remaining, current, solutions) # without the element
solutions = []
search([3, 34, 4, 12, 5, 2], 0, 9, [], solutions)
print(solutions) # [[3, 4, 2], [4, 5]]
The line with remaining < 0 avoids exploring a lot of branches. With long lists pruning can save millions of steps. Check it in Subsets with a target sum.
Example: well-formed parentheses
Generating all possible strings of ( and ) and keeping the valid ones would be very expensive. With backtracking only strings that are already correct so far are built: you can open while there are parentheses left to open, and close only if there are more open than closed.
def generate(n, current, opened, closed, result):
if len(current) == 2 * n:
result.append(current)
return
if opened < n: # can open
generate(n, current + "(", opened + 1, closed, result)
if closed < opened: # can close
generate(n, current + ")", opened, closed + 1, result)
result = []
generate(3, "", 0, 0, result)
print(result)
# ['((()))', '(()())', '(())()', '()(())', '()()()']
Here nothing has to be undone because current is a string passed new in each call (strings are immutable). You practise it in Well-formed parentheses. The number of solutions are the Catalan numbers: 1, 2, 5, 14, 42...
When to undo and when not
| If the state is... | Then... |
|---|---|
| a shared list or dictionary | you must undo when coming back (pop(), del) |
| a string, a number or a tuple (a new one is passed in each call) | no need to undo: each call has its own copy |
Typical mistakes
- Forgetting to undo the choice: the following solutions come out contaminated.
- Storing
currentinstead oflist(current). - Not putting the base case before the loop: infinite recursion.
- Pruning too much: discarding a branch that did have a solution. Prune only with conditions you are sure are definitive (like "the sum has already overshot" with positive numbers).