版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/82561538
给定一个无重复元素的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明:
- 所有数字(包括
target
)都是正整数。 - 解集不能包含重复的组合。
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解题思路
我们这个问题可以通过递归回溯的思想来解决。我们遍历candidates=[2,3,6,7]
,target=7
。我们先遍历到2
,这个时候我们如果结果中有2
的话,那么我们接下来的target=5
,一次下去,结果就是
2 2 2 2
我们发现这个时候target=-1
,显然不对,这个时候我们退到上一步,也就是
2 2 2
这个时候我们的target=1
,我们将剩余3,6,7
遍历一遍都没有我们想要的结果。接着我们再退回到上一步,也就是
2 2
这个时候我们的target=3
,我们依次遍历3,6,7
。我们发现3
满足条件,我们将2,2,3
加入到结果中。同理,我们将7
加入到结果中。
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
candidates.sort()
self._combinationSum(candidates, target, 0, list(), result)
return result
def _combinationSum(self, nums, target, index, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(index, len(nums)):
self._combinationSum(nums, target-nums[i], i, path+[nums[i]], res)
其实你也发现了,实际上当target < nums[0]
的时候我们就应该直接return
,这样我们又优化了这个代码。
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
candidates.sort()
self._combinationSum(candidates, target, 0, list(), result)
return result
def _combinationSum(self, nums, target, index, path, res):
if target == 0:
res.append(path)
return
if target < nums[0]:
return
for i in range(index, len(nums)):
self._combinationSum(nums, target-nums[i], i, path+[nums[i]], res)
但是上面的写法依然有一个问题,如果前两个元素是2,3
的话,第三个元素应该从3
之后的6,7
中寻找,但是我们通过target < nums[0]
,并没有将这种情况剔除,所以我们这个写法还不是最好的。那应该怎么做呢?改成下面这样就可以了
if path and target < path[-1]:
return
我们每次应该和path[-1]
去比较。这里的实现在c++
中存在一个陷阱,我们在写path[-1]
,应该这样写
if (!path.empty() and target < *(path.end() - 1)) return;
同样的,对于递归可以解决的问题,我们都应该思考是不是可以通过迭代解决。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates = sorted(set(candidates))
result = list()
stack = [(0, list(), target)]
cand_len = len(candidates)
while stack:
i, path, remain = stack.pop()
while i < cand_len:
if path and remain < path[-1]:
break
if candidates[i] == remain:
result.append(path + [candidates[i]])
stack += [(i, path + [candidates[i]], remain - candidates[i])]
i+=1
return result
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!