1 """ 2 Given a set of distinct integers, nums, return all possible subsets (the power set). 3 Note: The solution set must not contain duplicate subsets. 4 Example: 5 Input: nums = [1,2,3] 6 Output: 7 [ 8 [3], 9 [1], 10 [2], 11 [1,2,3], 12 [1,3], 13 [2,3], 14 [1,2], 15 [] 16 ] 17 """ 18 """ 19 第一层循环依次遍历nums列表中的数字 20 第二层遍历res列表中的元素 21 将每个元素进行深拷贝,复制一份 22 将复制的元素中添加nums中的数字 23 再将添加数字后的元素添加到结果list中 24 """ 25 class Solution: 26 def subsets(self, nums): 27 res = [[]] 28 for num in nums: 29 for temp in res[:]: # 这里的res[:]是遍历res中的子list 30 x = temp[:] # 这里是temp[:]深拷贝, temp为浅拷贝 31 #深拷贝是将值和地址一同拷贝, 32 #浅拷贝只拷贝值,值的所在地址是一样的 33 x.append(num) 34 res.append(x) 35 return res
原文:https://www.cnblogs.com/yawenw/p/12370047.html