在递归调用过程中追加时,全局列表突然更新

时间:2019-06-24 12:13:02

标签: python list recursion global

我在Leetcode平台上遇到了一个题为“组合总和”的问题,我需要在这里找到所有对,它们加起来等于作为程序输入提供的目标值。

在提供的代码中,在递归调用期间,只要目标等于成本,就需要将列表partialsol附加到全局列表结果中。但是,只要满足此条件,则在每次递归调用之后,都会更新结果列表,然后追加partialsol,并在所有递归调用完成之后,返回的结果列表为空。

class Solution(object):
    result = []

    def findpairs(self, partialsol, candidates, target, cost, start):
        if(cost == target):
            print(self.result)
            print(partialsol)
            self.result.append(partialsol)
            print(self.result)
            print('---------------')
            return
        else:
            for i in range(start, len(candidates)):
                c = candidates[i]   
                if((cost+c) > target):
                    continue
                partialsol.append(c)
                self.findpairs(partialsol, candidates, target, cost+c, i)
                partialsol.pop()
            return

    def combinationSum(self, candidates, target):
        partialsol = []
        self.findpairs(partialsol, candidates, target, 0, 0)
        return self.result

您的输入

candidates: [2,3,6,7]

target: 7

stdout:

[]

[2, 2, 3]

[[2, 2, 3]]

[[7]] #here the result list is getting updated from [[2,2,3]] to [[7]] even before appending.

[7]

[[7], [7]] #here the partialsol is appended but lost the previous list [[2,2,3]] as it is updated to [[7]].

Output

[[],[]] #returned result as empty lists of list

Expected

[[2,2,3],[7]]

0 个答案:

没有答案