📣 独立日限时特惠: VIP通行证立减$68
查看: 2193| 回复: 6
跳转到指定楼层
上一主题 下一主题
收起左侧

做Combination Sum II 遇到的一个python问题

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
以前用c++写的,现在用python重写的时候遇到很tricky的问题,我已经绕晕了,求python大神解释一下:
刚开始写的,在dfs()里面打印结果都是对的,但是传出来总是空的,比如题目给的例子跑出来就是[ [ ][ ][ ][ ] ]
  • class Solution:
  •     # @param candidates, a list of integers
  •     # @param target, integer
  •     # @return a list of lists of integers
  •     def combinationSum2(self, candidates, target):
  •         Solution.res = []
  •         candidates.sort()
  •         self.dfs(candidates,0,0,target,[])
  •         return Solution.res
  •     def dfs(self,candidates,index,s,target,solu):
  •         if s>target: return
  •         if s==target:
  •             return Solution.res.append(solu)
  •         while index < len(candidates):
  •             solu.append(candidates[index])
  •             self.dfs(candidates,index+1,s+candidates[index],target,solu)
  •             solu.pop()
  •             while index<len(candidates)-1 and candidates[index]==candidates[index+1]:
  •                 index+=1
  •             index+=1
  •         return





后来改成这样就可以了:
  •             solu.append(candidates[index])
  •             self.dfs(candidates,index+1,s+candidates[index],target,solu)
  •             solu.pop()

改成
  •             self.dfs(candidates,index+1,s+candidates[index],target,solu+[candidates[index]])



自己想了很久,越想越晕乎了,求python大神解释一下到底是什么原理?? 谢了啊

上一篇:leetcode又出新题了
下一篇:CTCI Question1.5问题
🔗
 楼主| woshidxfdxf 2014-10-23 05:53:37 | 只看该作者
全局:
求大神解惑啊
回复

使用道具 举报

🔗
manifold 2014-10-28 13:32:21 | 只看该作者
全局:
楼上的解释正确啊 list是mutable object, 作为参数传递给函数时, 传递的reference。 所以, pop的时候, 把已经append到res里的solu也pop了。

把line 16改为 return Solution.res.append(list(solu)) 即可。 为solu创建一个新的copy, 把copy push到res中去。
回复

使用道具 举报

🔗
 楼主| woshidxfdxf 2014-10-29 04:56:42 | 只看该作者
全局:
kinslayer 发表于 2014-10-27 14:27
因为你Solution.res.append(solu),此时Solution.res已经和solu相关了(pass by reference);你之后再solu.p ...

我又翻书看了看 确实是这样
之前一直没弄明白list1.append(list2)是shallow copy的
非常感谢!
回复

使用道具 举报

🔗
 楼主| woshidxfdxf 2014-10-29 04:58:07 | 只看该作者
全局:
manifold 发表于 2014-10-28 13:32
楼上的解释正确啊 list是mutable object, 作为参数传递给函数时, 传递的reference。 所以, pop的时候,  ...

非常感谢!
return Solution.res.append(list(solu)) 就是append的时候新建list复制solu,理解了
回复

使用道具 举报

🔗
Frankhappens 2014-10-29 09:29:09 | 只看该作者
全局:
传参和引用的问题么?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表