美文网首页
leetcode 78 python 子集

leetcode 78 python 子集

作者: 慧鑫coming | 来源:发表于2019-02-13 09:04 被阅读0次

传送门

题目要求

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

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

示例:

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

思路

构造嵌套列表[[]],遍历给定数组,每次将遍历到的元素,再遍历的加入到嵌套列表的元素,再将得到的新的元素加入到嵌套列表。

class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = [[]]
        for num in nums:
            # [:]前复制,为了不破坏被遍历数组
            for i in res[:]:
                temp = i[:]
                temp.append(num)
                res.append(temp)
        return res

相关文章

网友评论

      本文标题:leetcode 78 python 子集

      本文链接:https://www.haomeiwen.com/subject/nihreqtx.html