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.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
, A solution set is: [ [7], [2,2,3] ]
Example 2:
Input: candidates = [2,3,5],
target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
LeetCode:链接
回溯法习题:
LeetCode40:Combination Sum II(回溯)
LeetCode216:Combination Sum III(回溯)
LeetCode377:Combination Sum IV(动态规划)
让你判断有多少种呢就是动态规划,一旦让我们写出全部的组合那就是回溯。
回溯就是一直加进去数,满足条件就存下来,不满足呢就回退一步。
注意backtracking函数,利用for可以实现回溯。我们对数组进行了排序,所以for中一旦target<candidates[i],那么就代表着这个数组已经不可能和是target了,一定要设置break跳出这个循环,否则会一直进行下去,永无天日的!如果不排序,就要判断target<0,判断时间就会比较长!
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
ans, res = [], []
candidates.sort()
self.backtracking(candidates, target, 0, ans, res)
return res
def backtracking(self, candidates, target, start, ans, res):
if target == 0:
res.append(ans)
else:
for i in range(start, len(candidates)):
if target < candidates[i]:
break
self.backtracking(candidates, target-candidates[i], i, ans+[candidates[i]], res)