SDE & MLE Prep

216. Combination Sum III

Problem

Return every combination of k distinct numbers from 1–9 that adds up to n, each number used at most once.

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

Choose k distinct digits from 1–9 summing to n: combinations with i + 1 and pruning when the remainder goes negative.

Complexity: O(C(9, k)).

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res, path = [], []

        def bt(start, rest):
            if len(path) == k:
                if rest == 0:
                    res.append(path[:])
                return
            for d in range(start, 10):
                if d > rest:
                    break
                path.append(d)
                bt(d + 1, rest - d)
                path.pop()

        bt(1, n)
        return res