题目
给定一组候选数字(没有重复)和目标数字(target),找到候选数总和==目标的所有独特组合。
可以从候选数字中无限次数中选择相同的重复数字。
思路
利用栈来做,为了找独特的组合,不妨让结果中的数组都递增。(允许重复,因此不是单调递增)
解答
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort() #排序,后面可以节省时间
result = []
stack = []
for num in candidates:
if num == target:
result.append([num])
else:
stack.append(([num],target-num))
while stack:
path,remain = stack.pop()
if remain < path[-1]:
continue
for num in candidates:
if num < remain and num >= path[-1]:
stack.append((path+[num],remain-num))
if num == remain:
result.append(path+[num])
if num > remain:
continue
return result