首页 > 其他 > 详细

leetcode78 Subsets

时间:2020-02-27 00:21:28      阅读:50      评论:0      收藏:0      [点我收藏+]
 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

 

leetcode78 Subsets

原文:https://www.cnblogs.com/yawenw/p/12370047.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!