简体   繁体   English

不了解此递归python代码

[英]Not understanding this recursive python code

I recently was trying to figure out the answer to a question on code fights. 我最近试图找出有关代码争用问题的答案。 I eventually found a solution that works from this website: https://statyang.wordpresults.com/python-practice-51-combination-sum/ 我最终找到了可从以下网站使用的解决方案: https : //statyang.wordpresults.com/python-practice-51-combination-sum/

However, no matter how many print statements or debugging I do, I can't seem to figure out how 但是,无论我执行多少打印语句或调试,我似乎都无法弄清楚

target

is changing value somewhere in the 正在改变价值的某个地方

if target < candidates[i]:
    return

The whole purpose of the program is to have an input of an array, and including duplicates, output the different combinations of sums that add up to the target. 该程序的全部目的是输入一个数组(包括重复项),并输出加总到目标的总和的不同组合。

here is the code with all of the debugging print statements 这是所有调试打印语句的代码

class Solution2:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
    candidates.sort()
    result=[]
    self.DFS(candidates,target,0,result,[])
    return result

def DFS(self,candidates,target,start,result,intermedia):
    print "===== inside DFS method ============="
    print "candidates {0}".format(candidates)
    print "target: {0}".format(target)
    print "start {0}".format(start)
    print "result {0}".format(result)
    print "intermedia {0}".format(intermedia)
    if target==0:
        print ">>> inside if target==0"
        print "target==0 appending {0}".format(intermedia)
        result.append(intermedia)
        return
    for i in range(start,len(candidates)):
        print "=====inside for loop ========: i= {0}".format(i)
        print "target={0}, cadidates[i]={1}".format(target, candidates[i])
        if target<candidates[i]:
            print ">>> target < candidates[i] {0} < {1}".format(target, candidates[i])
            print "i before return {0}".format(i)
            return
        print "i after return {0}".format(i)
        print "======== preparing for recursion ========:"
        print "candidates {0}".format(candidates)
        print "new target: target - candidates[i]: {0} - {1} = {2}".format(target, candidates[i], target-candidates[i])
        print "new start: {0}".format(i)
        print "result {0}".format(result)
        print "new intermedia: intermedia + candidates[i]: {0} + {1} = {2}".format(intermedia, [candidates[i]], intermedia + [candidates[i]])
        print "i= {0} start= {1}".format(i, start)
        print "about to call recursion again!"
        self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]])

test2=Solution2()
print(test2.combinationSum([2, 4, 6, 8], 8))

here is the ending output 这是结束输出

[[2, 2, 2, 2], [2, 2, 4], [2, 6], [4, 4], [8]]

as you can see, each of these pairs add up to 8 如您所见,这些对中的每对加起来为8

so really confused as to how the value for target seems to change somewhere inside of the loop and always to a positive number even though it is always inserting 对于目标值似乎如何在循环内的某个位置变化并始终变为正数(即使它总是插入)感到非常困惑

 target - candidates[i]

inside of the recursive function 递归函数内部

The recursion starts with this call, self.DFS(candidates,target,0,result,[]) , where the parameter, intermedia , is an empty array. 递归从此调用self.DFS(candidates,target,0,result,[]) ,其中参数intermedia是一个空数组。

intermedia then accumulates another candidate whenever target is still greater than or equal to candidate[i] . 然后,只要target仍大于或等于candidate[i] intermedia就会累积另一个candidate The accumulation happens at the end of this line: self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]]) . 累积发生在此行的末尾: self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]])

Meanwhile, target is decreased for this particular call to represent that we've used the candidate in trying to reach the target number. 同时,针对此特定呼叫降低了target ,以表示我们已使用候选人来尝试达到目标数量。 So that when target==0 , we're ready to result.append(intermedia) , which is this particular accumulation of candidates. 因此,当target==0 ,我们准备好result.append(intermedia) ,这是候选人的这种特殊积累。 A full new set of recursive calls with different candidates is generated in each call by the for loop. for循环在每个调用中生成一组具有不同候选者的全新递归调用集。

target is only changing via the recursive call on this line: 目标仅通过此行上的递归调用进行更改:

self.DFS(candidates,target-candidates[i],i,result,intermedia+[candidates[i]]) self.DFS(候选人,目标候选人[i],i,结果,中间媒体+ [候选人[i]])

It's always positive because the program does this check before making the recursive call: 总是肯定的,因为程序在进行递归调用之前会执行以下检查:

  if target<candidates[i]: ... return 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM