78. Subsets (Medium)

Description:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]


Solution:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        if not nums:
            return [[]]
        
        nums.sort()
        storage = [[]] + [[i] for i in nums]
        last_l = 1
        last_r = len(storage)
        
        for layer in range(2,len(nums)+1):
            for i in storage[last_l:last_r]:
                for j in nums[::-1]:
                    if i[-1] == j:
                        break
                    else:
                        storage.append(i+[j])
            last_l,last_r = last_r,len(storage)
        
        return storage

Performance:

  • Runtime: 36 ms, faster than 95.83% of Python3 online submissions for Subsets.
  • Memory Usage: 13.3 MB, less than 54.55% of Python3 online submissions for Subsets.

你可能感兴趣的:(78. Subsets (Medium))