题目:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
题解:
遇到问题不要懵,不要懵,话说,这道题,真的,看好几次都觉得有点懵逼。
其实,这个就是比昨天的n的k个组合,更复杂的组合。所以总体来说,算法的大体思路是相同的。那不同之处,就是怎么判断 temp 的结束。
我的思路分三步:
1,一次遍历判断 candidates 中的元素,如果元素 item 小于target,则将其暂存到temp中。
2,更新 target = target - item
3,更新candidates,将其中大于target的元素remove掉
for i in range(size):
item = src[i]
if item < target:
temp.append(src[i])
tempList = removeitem(target, src[i:]) # 这个函数就是remove 函数
fun(tempList,target - src[i])
temp.pop()
OK。架子有了,
将其装进 函数里面。开始递归。
代码:
from typing import List
class Solution:
# 移除比target大的元素
def removeitem(self,target, src: List[int]):
res = src[:]
size = len(res)
i = 0
while i < size:
if res[i] > target:
res.remove(res[i])
size = len(res)
else:
i += 1
return res
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
temp = []
src = candidates[:]
def fun(src, target):
size = len(src)
for i in range(size):
item = src[i]
if item < target:
temp.append(src[i])
tempList = self.removeitem(target, src[i:])
fun(tempList,target - src[i])
temp.pop()
elif item == target:
temp.append(src[i])
res.append(temp[:])
temp.pop()
elif item > target:
continue
fun(src,target)
return res
if __name__ == '__main__':
res = Solution().combinationSum([8,7,4,3],11)
print(res)