39. 组合总和
##题目描述
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
思路
先给数组排序,想想成一棵树,根节点为空,第一层为数组的各个数字,然后子节点为不小于父节点的数字。具体实现为Node(数组,数组中最大数字的index,数组和),如果和小于target就入栈,如果相等就放入结果数组中,如果大于就无视。
代码
class Node:
def __init__(self, li=[], index=0, sum=0):
self.li = li
self.index = index
self.sum = sum
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
stack = []
res = []
candidates.sort()
for i, num in enumerate(candidates):
if num < target:
tmp = Node([num], i, num)
stack.append(tmp)
elif num == target:
res.append([num])
break
else:
break
while stack:
top = stack.pop()
for i in range(top.index, len(candidates)):
if top.sum + candidates[i] < target:
tmp = Node(top.li + [candidates[i]], i, top.sum + candidates[i])
stack.append(tmp)
elif top.sum + candidates[i] == target:
res.append(top.li + [candidates[i]])
break
else:
break
return res
执行效率
执行用时:
60 ms, 在所有 Python3 提交中击败了
77.48%的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了91.64%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。