【问题标题】:Append SubResult List To Result List将子结果列表附加到结果列表
【发布时间】:2021-12-30 15:07:23
【问题描述】:

我正在尝试解决 Leetcode Combinations Sum 问题,并且我已经使用递归方法。在这里粘贴我的方法

def combinationSum(candidates,target):
    N = len(candidates)
    FinRes = []
    SubRes = []
    def Helper(Ind,candidates,target,FinRes,SubRes):
        if(Ind == len(candidates)):
            if(target == 0):
                FinRes.append(SubRes.copy()) # Adding SubRes To FinRes
            return
        if(candidates[Ind] <= target):
            SubRes.append(candidates[Ind])
            Helper(Ind,candidates,target-candidates[Ind],FinRes,SubRes)
            SubRes.pop()
        Helper(Ind+1,candidates,target,FinRes,SubRes)
        
    Helper(0,candidates,target,FinRes,SubRes)
    return FinRes

candidates = [2,3,6,7]                                                                                              
target = 7
print(combinationSum(candidates,target))

在我的递归函数Helper 中,当target==0 时,我将我的SubRes 附加到FinRes。我试过FinRes.append(SubRes),但它没有附加到FinRes(它实际上是稍后附加和删除),后来我做了SubRes.copy()它工作正常。那么我怎样才能添加SubResappend

【问题讨论】:

  • 不@DanielHao 我正在学习递归。所以想这样做。
  • 好的。在帖子中尝试下一种方法。

标签: python python-3.x algorithm recursion combinations


【解决方案1】:

这个版本怎么样,你可以试试。

def combinationSum(self, candidates, target):
    candidates.sort()    # sort first to make later comparison easier 
    
    def helper(candidates, target):
        result = []      # each `sublist` is an answer to the reduced problem
        if candidates:
            for i, x in enumerate(candidates):
                if x < target:
                   sublist = helper(candidates[i:], target -x) # reduce the problem...
                   #print(sublist)
                   for sub in sublist:
                       sub.append(x)
                       result.append(sub)
                elif target == x:
                    result.append([x])
                # the subsequent x's will be larger than the target, so skip 
                else:
                    break
         return result
        
     result = helper(candidates, target)
     return result

【讨论】:

    猜你喜欢
    • 2017-03-28
    • 2018-08-15
    • 1970-01-01
    • 2021-06-07
    • 2012-03-10
    • 2021-01-11
    • 2020-06-20
    • 2014-06-13
    • 2019-02-11
    相关资源
    最近更新 更多