Combinations (n choose k)
Medium TimeO(k · C(n, k)) SpaceO(n)
A combination is a selection where order does not matter, so choosing 1 then 2 is the same as choosing 2 then 1 and must appear only once. Given n and k, return every way to choose k numbers from 1 to n. Each number may be chosen at most once, and there are exactly n-choose-k results.
Examples
Example 1
- Input
- n = 4k = 2
- Output
- Six ways to pick 2 of 4:
[[3,4],[2,4],[1,4],[2,3],[1,3],[1,2]]4 × 3 ÷ 2, the division removing each pair's mirror image.
Example 2
- Input
- n = 3k = 3
- Output
- Choosing all three leaves nothing to decide, so there is exactly one way.
[[1,2,3]]
The Code
function combine(n, k) {
if (k === 0) return [[]];
if (n < k) return [];
const withN = combine(n - 1, k - 1).map((c) => [...c, n]);
const withoutN = combine(n - 1, k);
return [...withN, ...withoutN];
}
combine(4, 2);Done
More like this
All backtracking examples (10) →- Permutations Fix each element first, then permute what remains.
- Subsets Every subset either includes the first element or it doesn’t.
- N-Queens Place a queen per row, backtracking the moment two attack.
- Gen parentheses Add “(” while you can, “)” only when it stays balanced.
- Combination sum Reuse candidates freely; prune the moment the remainder goes negative.
- Palindrome partition Cut off every palindromic prefix, then partition the rest.