Skip to content
Problem 77 · LeetCode 77(opens in a new tab)

Combinations

MediumBacktracking

You get two whole numbers, n and k. Return every way to choose k different numbers from 1, 2, ..., n.

A combination is a set, so [1, 3] and [3, 1] are the same one and must appear only once. The combinations can be returned in any order.

Example 1

Input:  n = 3, k = 2
Output: [[1, 2], [1, 3], [2, 3]]
Why:    each pair leaves out one of the 3 numbers
2 more examples and the constraints

Example 2

Input:  n = 4, k = 4
Output: [[1, 2, 3, 4]]
Why:    taking all four can be done one way

Example 3

Input:  n = 5, k = 1
Output: [[1], [2], [3], [4], [5]]
Why:    each number alone is a combination

Constraints

  • 1 ≤ n ≤ 20
  • 1 ≤ k ≤ n

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every subset as a bit maskO(2ⁿ · n)
  2. BacktrackingO(k · C(n, k))

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 20, k = 2Verdict
Every subset as a bit maskO(2ⁿ · n)
Tries far more than it keeps
BacktrackingO(k · C(n, k))
Best; touches only real answers

n = largest number, k = how many to choose, C(n, k) = number of combinations.

Edge cases to test

  • k equals n. Only one combination: every number, [1, 2, ..., n].
  • k is 1. n combinations, each a single number.
  • n is 1. n = 1, k = 1 gives [[1]].
  • Largest answer. n = 20, k = 10 has 184,756 combinations: the output alone is big, so avoid any extra work per answer.

Common mistakes

  • Starting each slot from 1 instead of from the number after the last pick, which produces [2, 1] as well as [1, 2].
  • Appending the path itself instead of a copy.
  • Forgetting to pop after the recursive call, so the path keeps growing.

How to talk through it

  1. 1Clarify. Do [1, 2] and [2, 1] count once? Does the output order matter?
  2. 2Name the size. There are C(n, k) answers, so any solution is at least that much work.
  3. 3Mention the masks. Every subset as bits works, but it scans all 2ⁿ of them.
  4. 4Code the backtracking. Increasing order removes duplicates; push, recurse, pop. Add the room-left bound.
  5. 5Test out loud. Run n = 3, k = 2 by hand, then k = n and k = 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?