zoukankan      html  css  js  c++  java
  • 【算法题11 求子集问题】

    1、来源:LeetCode78

    给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

    说明:解集不能包含重复的子集。

    示例:

    输入: nums = [1,2,3]
    输出:
    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]

    解决代码:

     1 class Solution:
     2     def subsets(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: List[List[int]]
     6         """
     7         res=[[]]
     8         for num in sorted(nums):
     9             res += [item+[num] for item in res]
    10         return res

    2、来源LeetCode90

    给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

    说明:解集不能包含重复的子集。

    示例:

    输入: [1,2,2]
    输出:
    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]

    解决代码:

     1 class Solution:
     2     def subsetsWithDup(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: List[List[int]]
     6         """
     7         res=[[]]
     8         nums.sort()
     9         for i in range(len(nums)):
    10             if i==0 or nums[i]!=nums[i-1]:
    11                 l=len(res)
    12             for j in range(len(res)-l,len(res)):
    13                 res.append(res[j]+[nums[i]])
    14         return res
  • 相关阅读:
    nodepad++的python环境变量设置
    notepad++怎么显示项目的目录树?
    转:Mysql explain
    转:Java NIO(3)
    转:Java NIO(2)
    转:Java NIO
    java 符号引用与直接引用
    Redis 基础命令
    适配器模式 & 装饰器模式
    classpath: spring 中的查找方式
  • 原文地址:https://www.cnblogs.com/yanmk/p/9074258.html
Copyright © 2011-2022 走看看