zoukankan      html  css  js  c++  java
  • 78. 子集

    78. 子集

    题意

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

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

    示例:

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

    解题思路

    1. 回溯:每一次递归都把当前的路径数组加入到最终的结果中,同时维护一个index,将index的值加入到当前路径数组中,将index+1往后递归;

    2. 迭代实现:思想和递归类似,取出一个值,将这个值加入到之前计算出来的所有子集中;

    实现

    class Solution(object):
       def subsets(self, nums):
           """
          :type nums: List[int]
          :rtype: List[List[int]]
          """
           result = []
           def helper(index, path):
               result.append(path)
               for idx in range(index, len(nums)):
                   helper(idx+1, path+[nums[idx]])
           
           helper(0, [])
           return result

       def subsets(self, nums):
           """
          :type nums: List[int]
          :rtype: List[List[int]]
          """
           res = [set()]

           for num in nums:
            # 将计算出来的子集中所有的子集加入num
               for i in range(len(res)):
                   if not res[i]:
                       res.append({num,})
    # 取并集
                   elif num not in res[i]:
                       res.append({num,} | res[i])
           return map(list, res)
         
    def subsets(self, nums):
           """
          :type nums: List[int]
          :rtype: List[List[int]]
          """
           return reduce(lambda t, n: [a + [n] for a in t] + t, nums, [[]])

  • 相关阅读:
    laytpl模板——怎么使用ajax与数据交互
    项目中遇到的几个日期转换的场景
    input可以自动换行吗???
    EL表达式 if 和 if else语句的写法
    小程序开发之背景图片的设置
    主流浏览器内核
    HTTP状态码
    (四)js数组方法一
    (效果二)js实现两个变量值的交换
    (十八)js控制台方法
  • 原文地址:https://www.cnblogs.com/George1994/p/7399776.html
Copyright © 2011-2022 走看看