Combinations
MediumTop Interview 150 BacktrackingProblem
You are given two whole numbers n and k. Return every group of exactly k
different numbers that can be picked from 1, 2, …, n.
The order inside a group does not matter, so [1, 2] and [2, 1] count as the same group.
The groups may be returned in any order.
Constraints
- 1 ≤ n ≤ 8
- 1 ≤ k ≤ n
Examples: pick one to animate
Solutions
TimeO(k · C(n, k))
SpaceO(k)
Time: Every call that is entered leads to at least one answer thanks to the loop limit, and each answer costs O(k) to copy, so the work is about C(n, k) times k.
Space: Besides the output, the path and the recursion are at most k numbers and k + 1 calls deep.
Pick numbers in increasing order: after choosing i, only numbers bigger than i
may follow. Stop the loop early once there are too few numbers left to fill the path, because that branch
could never reach size k.