Combination Sum III — LeetCode 216 Python Solution
- Problem
- #216
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | (C_{9}^k \times k) |
| Space | O(k) auxiliary |
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
On a study list
This problem is on LeetCode 75.
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.