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
该问题是一个寻找所有可能的、由1到9的数字组成的、且每个数字最多使用一次的k个数之和为n的组合的问题。解决方案是使用深度优先搜索(DFS)策略,从数字1开始递归地尝试所有可能的组合,将符合条件的组合添加到结果列表中。
291

被折叠的 条评论
为什么被折叠?



