03
Combinations / choose K (Backtracking Sub-pattern)
Choose exactly k items where order doesn't matter: pick them in increasing order, and prune when there aren't enough items left.
Signals in the problem statement
- ›
"choose k numbers from 1..n"
- ›
"k numbers that add up to n" from a small fixed range
- ›
each position draws from its own list (phone keypad letters)
What makes it different
Combinations is choose-k with the "enough numbers left" bound. Letter Combinations is different: position i picks from digit i's letters, so there is no start index, just recursion on the digit index (and empty input gives []). Combination Sum III is choose-k from 1..9 with a sum target: stop when the sum goes over or the count is already k.
Questions
ordered from “learn the idea” to “recognise it without help”- 1CombinationsWalkthroughMediumBasic Anchor·LeetCode #77
- 2Letter Combinations of a Phone NumberWalkthroughMediumBasic Reinforcement·LeetCode #17
- 3Combination Sum IIIWalkthroughMediumSlight Variation·LeetCode #216
Template
choose-k-template.cpp
// Choose K: pick items in increasing order (start index), so each group appears once.
// Prune when the numbers left can't fill the remaining slots.
void build(int n, int k, int start, vector<int>& path, vector<vector<int>>& out) {
if ((int)path.size() == k) { out.push_back(path); return; }
int need = k - path.size();
for (int i = start; i <= n - need + 1; i++) { // i > n-need+1 leaves too few numbers
path.push_back(i);
build(n, k, i + 1, path, out); // next pick must be larger
path.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> out;
vector<int> path;
build(n, k, 1, path, out);
return out;
}Remember this · Backtracking
Trigger
"All subsets / permutations / combinations", place items under rules (N-Queens, Sudoku), find a path in a grid.
Think
At each step, what are my choices, and how do I undo a choice?
Key question
What is my state, when is it complete, and when do I prune?