The 3 Backtracking Patterns Behind Most Interview Questions
Backtracking builds answers one choice at a time, explores where each choice leads, and undoes it before trying the next one.
Almost every backtracking question is a twist on one of these three patterns. Learn their decision trees and you can adapt them quickly.
1) Subsets
Generate every subset of a list. Each path from the root of the decision tree is a subset, so every node, not just the leaves, is part of the answer. Only choosing elements after the current index stops the same subset from appearing twice.
2) Combinations
Choose exactly k items out of n. The tree looks like the subsets tree, but you stop going deeper once the path holds k items, and only those full paths are answers.
3) Permutations
Produce every ordering of a list. Unlike subsets, order matters, so each level may pick any number not used yet. Only the leaves, where every number has been placed, are answers.