记一次浅拷贝的错误

时间:2021-11-01 04:11:07
 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]]