A quick reference for recursion and backtracking techniques and problems to practice. Recursion is a problem-solving approach where a function calls itself to solve smaller instances of the same problem. Backtracking extends recursion by systematically exploring all possible solutions and abandoning paths that cannot lead to a valid answer.These techniques are foundational to many areas of computer science. Recursion underlies tree traversals, divide-and-conquer algorithms, and dynamic programming. Backtracking powers constraint satisfaction problems like Sudoku, N-Queens, and combinatorial generation. In interviews, the ability to think recursively and structure backtracking solutions cleanly is a strong signal of problem-solving skill.
Key Concepts
The table below outlines the core concepts you need to understand for recursion and backtracking problems. Every recursive solution must have a base case and a recursive case. Backtracking adds the choose-explore-unchoose pattern on top of basic recursion.
Concept
Description
Base Case
When to stop recursion
Recursive Case
How to break down the problem
Choose-Explore-Unchoose
The backtracking pattern
Pruning
Skip invalid paths early
State
Track current path/choices
The Backtracking Template
Nearly all backtracking problems follow the same structure. You make a choice, recurse to explore that choice, and then undo (unchoose) the choice before trying the next option. This template works for generating subsets, permutations, combinations, and solving constraint problems:
Choose: Add the current option to your partial solution (e.g., add an element to the current subset).
Explore: Recurse with the updated state to continue building the solution.
Unchoose: Remove the current option to restore the state before trying the next option.
Pruning is the art of recognizing dead-end paths early and skipping them. Good pruning can dramatically reduce the search space. For example, in N-Queens, once you place a queen that attacks another, you can immediately abandon that branch without exploring further placements.