码迷,mamicode.com
首页 > 其他好文 > 详细

78.子集

时间:2020-06-06 13:17:42      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:too   回溯算法   end   python   itertools   bsp   ble   python库   ems   

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

示例:

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

]

思路1:python库函数

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
        for i in range(len(nums)+1):
            for tmp in itertools.combinations(nums, i):
                res.append(tmp)
        return res

思路2:迭代

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = [[]]
        for i in nums:
            res = res + [[i] + num for num in res]
        return res

思路3:回溯算法

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
        n = len(nums)
        
        def helper(i, tmp):
            res.append(tmp)
            for j in range(i, n):
                helper(j + 1,tmp + [nums[j]] )
        helper(0, [])
        return res  

 

链接:https://leetcode-cn.com/problems/subsets/solution/hui-su-suan-fa-by-powcai-5/

 

78.子集

标签:too   回溯算法   end   python   itertools   bsp   ble   python库   ems   

原文地址:https://www.cnblogs.com/USTC-ZCC/p/13054079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!