python - 全局列表在递归调用期间追加时突然更新
问题描述
我在 Leetcode 平台上遇到了一个名为“组合总和”的问题,我需要在其中找到所有总和为作为程序输入提供的目标值的对。
在提供的代码中,在递归调用期间,只要目标等于成本,就需要将列表 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]]
解决方案
推荐阅读
- python - 循环遍历列表并在python中调用API
- scrollbar - excel vba滚动条不断滚动
- node.js - Cloud SQL 连接从云运行失败
- python - os.walk 和 glob.glob 的区别
- c++ - 从 C 函数返回 Arduino 字符串是否安全?
- abap - 使用 FOR ALL ENTRIES 和 NOT EXISTS 的 SQL 语句不正确
- mysql - 如何在 MySQL 中 UNCOMPRESS 后保留转义字符?
- r - 文档以外的不同变量的主题比例
- php - 显示文章类别的名称
- css - 为什么我的第一个 svg 路径设置仅在 Safari 中恢复为原始状态?