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.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Algorithm
Use dfs solve it.
Code
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans = []
save = [0] * 9
def dfs(s, n, d):
nonlocal save, ans, k
if 0 == n and d == k:
ans.append(save[0:d])
for i in range(s, 10):
save[d] = i
if n >= i and d < k:
dfs(i+1, n-i, d+1)
dfs(1, n, 0)
return ans