sagelearnai

Combinations

Difficulty: Medium · Pattern: Backtracking · LeetCode #77

Return all combinations of k numbers chosen from 1..n, in any order.

Examples

text
n = 4, k = 2  →  [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
n = 1, k = 1  →  [[1]]

Hints

  1. Build each combination in increasing order so each set is produced exactly once.
  2. If you still need need more numbers, the next pick can be at most n − need + 1.

Approach

bt(start): if len(path) == k, record it. Otherwise try i from start to n − (k − len(path)) + 1.

That upper bound is the pruning step. It stops the recursion from exploring branches that can't possibly collect k numbers, and it can speed things up a lot when k is close to n. There are C(n, k) results, each of length k.

Complexity

Time: O(k · C(n,k)). Space: O(k).

Python solution
def combine(n, k):
    res, path = [], []
    def bt(start):
        if len(path) == k:
            res.append(path[:])
            return
        for i in range(start, n - (k - len(path)) + 2):
            path.append(i)
            bt(i + 1)
            path.pop()
    bt(1)
    return res
JavaScript solution
function combine(n, k) {
  const res = [], path = [];
  const bt = (start) => {
    if (path.length === k) { res.push([...path]); return; }
    for (let i = start; i <= n - (k - path.length) + 1; i++) { path.push(i); bt(i + 1); path.pop(); }
  };
  bt(1);
  return res;
}