Backtracking

Explores all possible choices recursively and 'backtracks' when a choice leads to a dead end.

The Approach

  • Define a recursive function that explores solutions from a given state.
  • Loop through all possible choices at the current step.
  • For each choice, add it to the current solution path ('choose').
  • Make a recursive call to explore further.
  • After the recursive call returns, undo the choice ('un-choose' or 'backtrack') to explore other paths.

Types of Backtracking

Permutations

Generate all possible orderings of a set of elements.

Choices

1
2
3

Current Path

Start exploring choices.

Solutions Found

Subsets

Generate all possible combinations of elements.

Choices

1
2
3

Current Path

Start exploring choices.

Solutions Found

Constraint Satisfaction

Find solutions that satisfy a set of constraints, like Sudoku or N-Queens.

Choices

1
2
3

Current Path

Start exploring choices.

Solutions Found

Common Problems

Permutations

Backtracking

Subsets

Backtracking

Combination Sum

Backtracking

Word Search

Backtracking

N Queens

Backtracking