Backtracking Pattern
Backtracking is an algorithmic technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point in time.
When to Use This Pattern
- Finding all possible solutions (combinations, permutations, subsets)
- Constraint satisfaction problems (N-Queens, Sudoku)
- Problems where you need to explore all possibilities
- When you need to undo choices and try alternatives
- Combinatorial problems
Key Concepts
Backtracking follows these steps:
- Choose: Make a choice
- Explore: Recursively solve the problem with the choice
- Unchoose: Undo the choice (backtrack) and try the next option
Visual Representation - Permutation Tree
Backtracking - Generating Permutations of [1, 2, 3]
Backtracking Principle: Systematically explore all possibilities by making choices, exploring recursively, and undoing (backtracking) when a path doesn't lead to a solution. This ensures we find all valid solutions without missing any.
Template
def backtrack(current_state, choices):
# Base case: solution found
if is_solution(current_state):
add_to_results(current_state)
return
# Try each choice
for choice in choices:
# Make choice
current_state.append(choice)
# Check if valid (pruning)
if is_valid(current_state):
# Explore
backtrack(current_state, remaining_choices)
# Unchoose (backtrack)
current_state.pop()