Combinations (LeetCode 77): Solution and Explanation

Medium
Backtracking

Given two integers n and k, return every possible way to choose k distinct numbers from the range 1 to n. Order does not matter, so [1, 2] and [2, 1] are the same combination and should appear only once.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

One brute force is to generate every subset of 1 to n and keep only the ones of size k. That enumerates 2^n subsets even when k is small, and most of them are thrown away. Another is to generate ordered sequences of length k and remove duplicates, which is even more wasteful because every combination appears k! times.

The duplicates go away if you only ever build combinations in increasing order. Every unordered set of numbers has exactly one increasing arrangement, so if each new number you pick is larger than the last one, you produce each combination exactly once. In practice that means each recursive call takes a start value and only considers numbers from start to n.

Backtracking turns that idea into code. Keep a list current holding the numbers picked so far. At each level, try each candidate i from start to n: add it, recurse with start = i + 1 so the next pick is larger, then remove it so the next candidate can take its place. When current reaches length k, append a copy to the results. The copy matters, because current keeps changing after you record it.

Approach: Backtracking in increasing order

  1. Create an empty result list and define backtrack(start, current).
  2. If len(current) == k, append a copy current[:] to result and return.
  3. Otherwise loop i from start to n inclusive.
  4. Append i to current, then call backtrack(i + 1, current) so every later pick is larger than i.
  5. After the call returns, pop i to undo the choice before trying the next candidate.
  6. Start with backtrack(1, []) and return result.

Step-by-step example

n = 4, k = 2
  1. Pick 1, giving [1]. The next level tries 2, 3 and 4 and records [1, 2], [1, 3] and [1, 4].
  2. Pop 1 and pick 2, giving [2]. The next level tries 3 and 4 and records [2, 3] and [2, 4].
  3. Pop 2 and pick 3, giving [3]. The next level tries 4 and records [3, 4].
  4. Pop 3 and pick 4, giving [4]. The next level starts at 5, which is past n, so nothing is recorded.
  5. The result is [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]], which is all C(4, 2) = 6 combinations.

Code: Python, Java, C++

1class Solution:
2    def combine(self, n: int, k: int) -> List[List[int]]:
3        result = []
4
5        def backtrack(start: int, current: List[int]):
6            if len(current) == k:
7                result.append(current[:])
8                return
9
10            for i in range(start, n + 1):
11                current.append(i)
12                backtrack(i + 1, current)
13                current.pop()
14
15        backtrack(1, [])
16        return result

Time and space complexity

Time

O(k × C(n, k))

There are C(n, k) combinations and copying each one costs O(k). Because this loop does not prune, it also visits prefixes that can never reach length k, like [4] above. For most inputs that overhead is a small factor, but when k is close to n the number of visited prefixes can approach 2^n, which the pruned loop in the pitfalls avoids.

Space

O(k)

The recursion depth and the current list are both at most k. The output itself takes O(k × C(n, k)) memory, which is unavoidable.

Other approaches

Include or exclude recursion (time O(k × C(n, k)), space O(k))

For each number from 1 to n, branch into taking it or skipping it, and record when k numbers are taken. It is the subset recursion with a size limit and pairs naturally with the pruning rule of stopping when too few numbers remain.

Library combinations (time O(k × C(n, k)), space O(k))

In Python, itertools.combinations(range(1, n + 1), k) produces the same output in lexicographic order. It is ideal in production code, but interviews usually expect you to write the backtracking yourself.

Common mistakes

  • Appending current instead of a copy. Every entry in result would then point to the same list, which ends up empty after all the pops.
  • Recursing with start instead of i + 1. That allows repeated or decreasing picks, which produces duplicates like [2, 1].
  • Not pruning when speed matters. Limiting the loop to range(start, n - (k - len(current)) + 2) skips starts that cannot leave enough numbers to finish the combination.
  • Looping to n exclusive in Python. The range must be range(start, n + 1) so that n itself can be chosen.

Frequently asked questions

How many combinations does the function return?

Exactly C(n, k) = n! / (k! × (n - k)!). For example, n = 4 and k = 2 gives 6 combinations.

What is the difference between combinations and permutations here?

Combinations ignore order, so each set appears once. Permutations count every ordering separately, so the same set of k numbers would appear k! times.

Why pass i + 1 as the next start?

It forces every combination to be built in strictly increasing order. Each unordered set has exactly one increasing order, so no duplicates are generated and no deduplication step is needed.