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, [[]])

  • 相关阅读:
    指针
    第一条:了解Objective-C语言的起源
    Java项目怎么使用Swagger生成API文档?
    springmvc 中@Controller和@RestController的区别
    Java ExecutorService四种线程池的例子与说明
    怎样解决Myeclipse内存溢出?
    过时date.toLocaleString()的解决方法
    maven中修改可用的版本
    String转换为Map
    tomcat在Debug模式下无法启动解决办法
  • 原文地址:https://www.cnblogs.com/George1994/p/7399776.html
Copyright © 2011-2022 走看看