40. 组合总和 II
题目描述
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
思路
排序,想象成数,根节点为空,第一层为各个数字,子节点是父节点之后的数字。Node(数组,父节点的index,数组的和),防止重复的办法是比较tmpNode和stack[-1]的数组是否一样,不一样才入栈。
代码
class Node:
def __init__(self, li=[], index=0, sum=0):
self.li = li
self.index = index
self.sum = sum
class Solution:
def combinationSum2(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)
if stack == [] or tmp.li != stack[-1].li:
stack.append(tmp)
elif num == target:
res.append([num])
break
else:
break
while stack:
top = stack.pop()
for i in range(top.index + 1, len(candidates)):
if top.sum + candidates[i] < target:
tmp = Node(top.li + [candidates[i]], i, top.sum + candidates[i])
if stack == [] or tmp.li != stack[-1].li:
stack.append(tmp)
elif top.sum + candidates[i] == target:
res.append(top.li + [candidates[i]])
break
else:
break
return res
执行效率
执行用时:
52 ms, 在所有 Python3 提交中击败了72.10%的用户
内存消耗:
14.8 MB, 在所有 Python3 提交中击败了92.43%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。