码迷,mamicode.com
首页 > 其他好文 > 详细

记一次浅拷贝的错误

时间:2018-03-11 20:53:21      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:引用   结果   gpo   app   list   elf   pen   tco   class   

 1 import copy
 2 class Solution(object):
 3     def subsets(self, nums):
 4         """
 5         :type nums: List[int]
 6         :rtype: List[List[int]]
 7         """
 8         result = [[]]
 9         self.generate(0,[],result,nums)
10         return result
11     def generate(self,k,item,result,nums):
12         if k > len(nums)-1:
13             return        
14         item.append(nums[k])
15         result.append(copy.deepcopy(item))#result.append(item)        
16         self.generate(k+1,item,result,nums)
17         item.pop()
18         self.generate(k+1,item,result,nums)

leetcode刷题时遇到了78题Subset,写了上面的代码,在第15行最开始用了注释里的result.append(item),把item的引用(地址)传给了result,结果每次递归result中除了原有的‘[]’元素,其他都同步在变。

下面是nums=[1,2,3]时,使用result.append(item)语句的过程

item: [1]
result: [[], [1]]
item: [1, 2]
result: [[], [1, 2], [1, 2]]
item: [1, 2, 3]
result: [[], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
item: [1, 3]
result: [[], [1, 3], [1, 3], [1, 3], [1, 3]]
item: [2]
result: [[], [2], [2], [2], [2], [2]]
item: [2, 3]
result: [[], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]]
item: [3]
result: [[], [3], [3], [3], [3], [3], [3], [3]]

下面是深拷贝时的过程

item: [1]
result: [[], [1]]
item: [1, 2]
result: [[], [1], [1, 2]]
item: [1, 2, 3]
result: [[], [1], [1, 2], [1, 2, 3]]
item: [1, 3]
result: [[], [1], [1, 2], [1, 2, 3], [1, 3]]
item: [2]
result: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2]]
item: [2, 3]
result: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3]]
item: [3]
result: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

 

记一次浅拷贝的错误

标签:引用   结果   gpo   app   list   elf   pen   tco   class   

原文地址:https://www.cnblogs.com/imageSet/p/8545307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!