DSA Master › Topic 10
Recursion & Backtracking
Backtracking is a DFS over a tree of decisions. At each level you choose an option, recurse, then undo the choice. Draw the recursion tree first. Once you can see it, the code mostly writes itself.
Concepts
- Recursion trees
- Choose / explore / unchoose
- Pruning
- Duplicate handling
How to recognise it
- The problem asks for all subsets, permutations, combinations or partitions.
- You're placing items under constraints (N-Queens, Sudoku, word search).
- The input is small (n ≤ ~15–20), which hints that exponential time is expected.
Common pitfalls
- Add a copy of path to the result (new ArrayList<>(path)), not the list itself.
- Sort the input first when you need to skip duplicates.
Problems
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Letter Combinations of a Phone Number (Medium)
- Palindrome Partitioning (Medium)
- N-Queens (Hard)
- Word Search (Medium)