• 记一次浅拷贝的错误


     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]]
  • 相关阅读:
    49. Group Anagrams
    43. Multiply Strings
    22. Generate Parentheses
    17. Letter Combinations of a Phone Number
    8. String to Integer (atoi)
    【转】C#中base关键字的几种用法:base()
    【转】C#中virtual和abstract的区别
    [转]C#中的abstract 类和方法
    【转】C#虚方法virtual详解
    【转】C#中protected用法详解
  • 原文地址:https://www.cnblogs.com/imageSet/p/8545307.html
Copyright © 2020-2023  润新知