zoukankan      html  css  js  c++  java
  • leetcode78 Subsets

     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         import copy
    28         res = [[]]
    29         for num in nums:
    30             for temp in res[:]: # 这里的res[:]是遍历res中的子list
    31                 x = temp[:]# 这里是temp[:]深拷贝,  temp为浅拷贝
    32                 # !!!可以替换成:x = copy.deepcopy(temp)
    33                 #深拷贝是将值和地址一同拷贝,
    34                 #浅拷贝只拷贝值,值的所在地址是一样的
    35                 x.append(num)
    36                 res.append(x)
    37         return res
    38 
    39 if __name__ == '__main__':
    40     a = Solution()
    41     x = a.subsets([1, 2, 3])
    42     print(x)
  • 相关阅读:
    ext4.2常用的几种弹框
    oracle的批量操作sql语句
    ztree异步加载树节点
    shiro接口对象介绍
    jquery记住密码
    整合ssm框架
    redis中 Could not get a resource from the pool 异常解决
    redis的安装
    centos下tomcat的安装
    centos下MySQL的安装
  • 原文地址:https://www.cnblogs.com/yawenw/p/12370047.html
Copyright © 2011-2022 走看看