难度:Medium ?:661
题目
找出所有k个可能的数的组合,使其加和为n。要求
- 所用数字在1~9
- 数字无重复
思路
如果不想用递归,可以利用栈来解决。
对于数字不可重复的问题,思路是让最终的结果里的数字按从小到大顺序排列。
解答
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = list()
stack = list()
for i in range(1,10):
stack.append(([i],n-i))
while stack:
path, remain = stack.pop()
if remain <= path[-1] or len(path)==k:
continue
for i in range(path[-1]+1,10):
if len(path) == k-1 and i==remain:
result.append(path+[i])
continue
else:
stack.append((path+[i],remain-i))
return result