leetcode 每日一题 39. 组合总和

回溯法

思路:

①先对给定数组排序

②从头遍历数组的每一个值,当这个值小于target时,压入数组pathList,target减去当前值,继续从数组当前值的位置开始遍历(这里涉及到对数组进行剪枝处理,为了去重),当target为0时,将数组pathList压入数组res,遍历结束后返回res

例如:

 

      candidates = [2,3,6,7], target = 7,

 

代码:

 

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        if target == 0:
            return
        candidates.sort()
        res = []
        pathList = []
        self.process(candidates,0,len(candidates),res,pathList,target)
        return res
    
    def process(self,candidates,begin,size,res,pathList,target):
        if target<0:
            return
        if target == 0:
            res.append(pathList[:])
        else:
            for i in range(begin,size):
                if candidates[i]<=target:
                    pathList.append(candidates[i])
                    self.process(candidates,i,size,res,pathList,target-candidates[i])
                    pathList.pop()

 

  

 

posted @ 2020-05-21 15:06  nil_f  阅读(119)  评论(0编辑  收藏  举报