leetcood学习笔记-39-组合总和

题目描述:

 方法一:

class Solution:
    def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int

            :rtype: List[List[int]]
            """
            ans=[]
            n=len(candidates)
            if candidates==[]: return []
            for i in range(n):
                if candidates[i]==target:
                    ans.append([candidates[i]])
                elif candidates[i]<target:
                    l=self.combinationSum(candidates[i:],target-candidates[i])
                    for x in l:
                        x.append(candidates[i])
                    ans+=l
            return ans

 另:

class Solution:
    def combinationSum(self, candidates, target: int):
        candidates.sort()
        n = len(candidates)
        res = []
        def backtrack(i, tmp_sum, tmp):
            if tmp_sum > target or i == n:
                return
            if tmp_sum == target:
                res.append(tmp)
                return
            for j in range(i, n):
                if tmp_sum + candidates[j] > target:
                    break
                backtrack(j,tmp_sum + candidates[j],tmp+[candidates[j]])
        backtrack(0, 0, [])
        return res

 

posted @ 2019-03-23 20:41  oldby  阅读(163)  评论(0编辑  收藏  举报