VISUALGO//PROBLEMS
combination sum iii · backtrackingmedium
digitsk = 3n = 7
1
2
3
4
5
6
7
8
9
path
·
·
·
sum 0 / 7
result · 0 / 1
ELEMENTS
k
n
Python
def combinationSum3(k: int, n: int) -> list[list[int]]:
result = []
def backtrack(start: int, path: list[int], total: int) -> None:
if len(path) == k:
if total == n:
result.append(path[:])
return
for digit in range(start, 10):
if total + digit > n:
break
path.append(digit)
backtrack(digit + 1, path, total + digit)
path.pop()
backtrack(1, [], 0)
return result