InterviewPrepKit

Home / Coding / Backtracking

Combinations

medium Original β†—
Solving tips
  • This is the skeleton under Combination Sum and Subsets: carry a start value and recurse with v+1 so increasing order is the canonical form and no duplicates arise.
  • Add the counting prune: if you still need m = k - len(path) values, only start values up to n - m + 1 can finish, which trims every dead branch at O(1).
  • Know both framings: slot-centric (which value fills the next slot) and value-centric include/exclude binary recursion mirroring C(n,k)=C(n-1,k-1)+C(n-1,k).
  • Time is O(C(n,k)*k) with O(k) recursion depth; append path.copy() at the leaf, not path itself.

Problem

Given two integers n and k, return all combinations of k distinct numbers chosen from the range 1..n (inclusive). Each combination is a set β€” [1,2] and [2,1] are the same combination and must appear only once. You may return the combinations, and the numbers inside each one, in any order.

Examples

  • n = 4, k = 2 β†’ [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] β€” all C(4,2) = 6 pairs.
  • n = 1, k = 1 β†’ [[1]] β€” the only choice.
  • n = 5, k = 5 β†’ [[1,2,3,4,5]] β€” choosing everything leaves exactly one combination.

Constraints

  • 1 <= n <= 20
  • 1 <= k <= n

The output itself can hold C(20,10) β‰ˆ 184,756 combinations of length 10 β€” the answer size is exponential, so the goal is generating each combination exactly once with as little wasted exploration as possible.

Think about it first

Hint 1 How do you avoid emitting both [1,2] and [2,1]? Decide on a canonical form β€” say, strictly increasing β€” and only ever generate that form.
Hint 2 Build the combination left to right: after placing the number v, the next slot may only use numbers greater than v. What two parameters does the recursion need?
Hint 3 Prune hopeless branches by counting: if you still need m more numbers but fewer than m candidates remain above your current start, no leaf below can succeed β€” the loop bound can encode this directly. Alternatively, think per number: 1..n each either joins the combination or doesn't, with a budget of k joins.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.