Trees & Recursion
Backtracking
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
all combinationspermutationssubsetsgeneraten-queensvalid arrangements
Practice
Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.
Ask yourself
- Enumerate ALL valid configurations?
- Permutations / combinations / subsets / placements?
- Choose → recurse → un-choose.
Classic problem
Permutations (LeetCode 46) — return every ordering of a distinct nums. Pick an unused
number, recurse, then put it back so the next branch can use it.
Input: nums = [1, 2, 3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] — all 6 orderings of 3 elements.
Common pitfalls
Forgetting to undo the choice after recursion.
Appending a reference instead of a copy of
path.