MediumNo. 0216

Combination Sum III — LeetCode 216 Python Solution

Topics
Array, Backtracking
On a study list
LeetCode 75
Reading time
3 min

The problem

Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once.

Example

Input
k = 3, n = 7
Output
[[1,2,4]]
Explanation
1 + 2 + 4 = 7

Python solution

PythonSolution
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        def dfs(i: int, s: int):
            if s == 0:
                if len(t) == k:
                    ans.append(t[:])
                return
            if i > 9 or i > s or len(t) >= k:
                return
            t.append(i)
            dfs(i + 1, s - i)
            t.pop()
            dfs(i + 1, s)

        ans = []
        t = []
        dfs(1, n)
        return ans

Complexity

Time
(C_9k × k)
Space · auxiliary
O(k)

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 216. Combination Sum III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0039Combination SumMedium
0212Word Search IIHard
0040Combination Sum IIMedium
0046PermutationsMedium
0047Permutations IIMedium
0051N-QueensHard

Frequently asked questions

How hard is LeetCode 216. Combination Sum III?

LeetCode 216. Combination Sum III is rated Medium on LeetCode.

What is the time complexity of LeetCode 216. Combination Sum III?

The Python solution on this page runs in (C_{9}^k \times k).

What is the space complexity of LeetCode 216. Combination Sum III?

The Python solution on this page uses O(k) auxiliary space.

What topics does LeetCode 216. Combination Sum III cover?

LeetCode 216. Combination Sum III is tagged Array and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.