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

原文地址:https://www.cnblogs.com/George1994/p/7399776.html