39. 组合总和

题目来源:

        leetcode题目:39. 组合总和 - 力扣(LeetCode)

解题思路:

       递归获得组合数,通过全局变量记录已经计算过的从而减少递归次数。注意去重。

解题代码:

#python3
class Solution:
    combines=[[]]
    def getDistinct(temp:List[List[int]]):
        for i in range(len(temp)):
            temp[i].sort()
        temp.sort()
        res=[]
        res.append(temp[0])
        for i in range(1,len(temp)):
            if temp[i]!=res[len(res)-1]:
                res.append(temp[i])
        return res

    def getRes(candidates:List[int],target:int)->List[List[int]]:
        res=[]
        for j in range(len(candidates)-1,-1,-1):
            i=1
            can=candidates[j]
            while target-i*can>=0:
                temp=target-i*can
                if temp==0:         
                    res.append([can]*i)
                else:
                    if len(Solution.combines[temp])==0:#combines中不存在该值
                        Solution.getRes(candidates,temp)
                    if Solution.combines[temp][0]==-1:  #已计算过但无法满足要求
                        pass
                    else:       #存在并且可以满足要求
                        for k in Solution.combines[temp]:
                            res.append([can]*i+k)
                i=i+1
        if len(res)==0:
            Solution.combines[target]=[-1]
        else:
            res=Solution.getDistinct(res)
            Solution.combines[target]=res
        return res

    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        Solution.combines=[[]]*(target+1)
        return Solution.getRes(candidates,target)
        
 
  

总结:

        丑陋的代码。另外,感觉可以递推?(有点类似斐波那契数列)

        官方题解是搜索回溯。选(选的话选几次)或者不选当前元素。


你可能感兴趣的:(LeetCode,刷题,LeetCode)