leetcode 78 python 子集

2019-02-13  本文已影响0人  慧鑫coming

传送门

题目要求

给定一组不含重复元素的整数数组 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
上一篇 下一篇

猜你喜欢

热点阅读