LeetCode 78 子集 python

题目描述

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

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

样例

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

想法一:
创建一个内函数 通过遍历start到nums的长度 遍历递归调用函数 然后加入到res中

class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        def temp(start, num):
            res.append(num)
            for i in range(start, len(nums)):
                temp(i+1, num+[nums[i]])
        temp(0, [])
        return res

想法二:
参考了别人代码 这个思路很简单 就是依次遍历nums列表中的数字 双重循环 第二重遍历res列表中的元素 给每个元素中添加nums中的数字 下面举个例子 比如按照样例中[1,2,3]

初始化 [ [ ] ]
第一次大循环完 [ [ ], [1] ]
第二次大循环完 [ [ ], [1], [2], [1,2] ]
第三次大循环完 [ [ ], [1], [2], [3], [1,3], [1,2], [2,3], [1,2,3] ]
class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = [[]]
        for num in nums:
            for temp in res[:]:
                x = temp[:]
                x.append(num)
                res.append(x)
        return res

最后

刷过的LeetCode源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值