leetcode - 78. Subsets

Description

Given an integer array nums of unique elements, return all possible
subsets
(the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

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

Input: nums = [0]
Output: [[],[0]]

Constraints:

1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.

Solution

Recursive, subset of A is: f(A) = [[A[0]] + f(A[1:]) + concate[[[A[0]]], f(A[1:])]. Use a memo to speed up

Time complexity: n ! n! n!
Space complexity: n ! n! n!

Code

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        memo = {}
        def helper(index: int) -> list:
            if index in memo:
                return memo[index]
            if index == len(nums) - 1:
                memo[index] = [[nums[index]]]
            else:
                res = [[nums[index]]]
                right_subset = helper(index + 1)
                res += right_subset
                res += [[nums[index]] + item for item in right_subset]
                memo[index] = res
            return memo[index]
        return helper(0) + [[]]

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)