SDE & MLE Prep

77. Combinations

Problem

Return every combination of k distinct numbers chosen from 1…n, in any order.

Example: n = 4, k = 2 → [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Choose k of 1..n. Prune: only start values that leave enough numbers to finish (i ≤ n − (k − len(path)) + 1).

Complexity: O(k · C(n, k)).

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        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