#77

Combinations

Medium Backtracking with pruning

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return all ways to choose k numbers from 1..n (order doesn't matter).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: all ways to choose k numbers from 1..n.

Why this works: pick in increasing order so each set appears once; stop early when not enough numbers remain.

Example: n = 4, k = 2

[1,2] [1,3] [1,4] [2,3] [2,4] [3,4]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

No pruning — still correct, but explores many dead branches.

Solve on LeetCode ↗
Complexity
  • Time: O(k · C(n, k)).
  • Space: O(k).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon