LeetCode 78. Subsets (Python)

来源:互联网 发布:mysql 5.7.20安装教程 编辑:程序博客网 时间:2024/06/05 06:26

题目描述:
Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

思路:
递归思路是输入包含有n个元素的列表的输出结果是包含有n-1个元素的列表的输出结果(除了空集)每一个都加上第n个元素,并在最后加上只有单独第n个元素的列表。

AC代码:

class Solution(object):    def subsets(self, nums):        """        这里没有写成递归形式,而是采用了一下深拷贝        :type nums: List[int]        :rtype: List[List[int]]        """        import copy        def sub(num):            temp = copy.deepcopy(res)            if len(res) == 0:                res.append([num])            else:                for x in temp:                    x.append(num)                    res.append(x)                res.append([num])        res = []        for i in range(len(nums)):            sub(nums[i])        res.append([])        return res