题目描述
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
对与一个给定的数组
candidates
(无重复数)、一个目标值target
,求得所有排列唯一的组合数。其中candidates
中元素可以出现多次。可以假设candidates是整数
例子
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
2019-06-12 深度优先
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def DFS(candidates,target,tmp):
if target==0:
res.append(tmp)
return res
for i in range(len(candidates)):
if target>=candidates[i]:
DFS(candidates[i:],target-candidates[i],tmp+[candidates[i]])
else:
break
candidates.sort()
res = []
DFS(candidates,target,[])
#print(res)
return res
S = Solution()
candidates = [2,3,6,7]
target = 7
S.combinationSum(candidates,target)
结果分析
Runtime: 28 ms, faster than 99.91% of Python online submissions for Combination Sum.
Memory Usage: 11.7 MB, less than 81.17% of Python online submissions for Combination Sum.
总结
这题与之前的TwoSum、ThreeSum
等实质上是同一种题,但是由于需要找出所有的组合、并且元素的使用次数无限制,导致没办法按照之前的双指针夹逼实现。刚开始拿到这一题,说实在的不会做,基本上是没思路。这里推荐B站博主的动态示意过程LeetCode 39. Combination Sum 中文,看了之后才明白原来是深度优先算法,涉及回溯等操作。清楚整体思路后,直接在网页上编写代码。
自认语言能力不足,描绘起来可能晦涩难懂,暂且不表。