Skip to content

Latest commit

 

History

History
61 lines (54 loc) · 1.42 KB

78.md

File metadata and controls

61 lines (54 loc) · 1.42 KB

题目地址

https://leetcode-cn.com/problems/subsets/

解答1

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        """
            子集

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

            输入: nums = [1,2,3]
            输出:
            [
              [3],
              [1],
              [2],
              [1,2,3],
              [1,3],
              [2,3],
              [1,2],
              []
            ]
        """
        res = [[]]
        for n in nums:
            for r in res[:]:
                res.append(r[:])
                r.append(n)

        return res

解答2

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        """
            子集

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

            输入: nums = [1,2,3]
            输出:
            [
              [3],
              [1],
              [2],
              [1,2,3],
              [1,3],
              [2,3],
              [1,2],
              []
            ]
        """
        from itertools import combinations
        return sum([list(combinations(nums, i)) for i in range(len(nums) + 1)], [])