Leetcode 90. Subsets II
Explanation for Leetcode 90 - Subsets II, and its solution in Python.
Problem
Example:
1
2
3
4
5
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Input: nums = [0]
Output: [[],[0]]
Approach
Similar to the subset question, we can get the subset by first sorting the array, then running DFS.
Here is the Python code for the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums.sort()
        def dfs(i, arr):
            if i == len(nums):
                res.append(arr.copy())
                return
            if arr in res:
                return
            dfs(i+1, arr+[nums[i]])
            dfs(i+1, arr)
        dfs(0, [])
        return res     
Time Complexity and Space Complexity
Time Complexity: $O(2^n)$
Space Complexity: $O(n)$
 This post is licensed under  CC BY 4.0  by the author.