思路:
https://leetcode-cn.com/problems/combination-sum/solution/hui-su-jian-zhi-jian-zhi-hou-9394zhu-xing-jie-shi-/
回溯法+排序剪枝
为了对算法进行剪枝处理,首先对candidatescandidates排序
特判,若candidatescandidates为空,则返回[][]
回溯函数helper()helper(),传入参数:下一加和索引ii,当前已加和数组tmptmp,下一目标targettarget
若target0target0,说明当前和满足条件,将当前加和数组tmptmp加入resres,并return。
剪枝 因为已经将candidatescandidates排序,所以当下一目标小于下一待加和数时,return。并且当下一待加和索引inin时,return。为了防止数组越界,将条件inin放在target<candidates[i]target<candidates[i]之前,进行截断。
因为可重复调用元素,所以helper(i,tmp+[candidates[i],target-candidates[i]])helper(i,tmp+[candidates[i],target−candidates[i]]),继续重复调用自身。
调用数组中下一元素,寻找新答案。helper(i+1,tmp,target])helper(i+1,tmp,target])。
执行helper(0,[],target)helper(0,[],target),并返回resres
作者:zhu_shi_fu
链接:https://leetcode-cn.com/problems/combination-sum/solution/hui-su-jian-zhi-jian-zhi-hou-9394zhu-xing-jie-shi-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
if not candidates:
return []
n = len(candidates)
res = []
candidates.sort()
def helper(i,tmp,target):
if target==0:
res.append(tmp)
return
if i == n or target<candidates[i]:
return
helper(i,tmp+[candidates[i]],target - candidates[i])
helper(i+1,tmp,target)
helper(0,[],target)
return res