Subsets II

Problem

Given an integer array nums that may contain duplicates, 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,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

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

Intuition

The problem requires finding all possible subsets (the power set) of a given integer array nums that may contain duplicates. The key is to ensure that the solution set does not contain duplicate subsets. This involves using a depth-first search (DFS) approach to explore all possible combinations while avoiding duplicates.

Approach

Sort the Array:

Sort the array nums. Sorting helps in identifying duplicates and ensures that identical elements are adjacent.
Initialize Result List:

Create an empty list res to store the resulting subsets.
DFS Function:

Implement a DFS function (dfs) that takes an index i as an argument.
The base case is when i is equal to or exceeds the length of the sorted array. In this case, add a copy of the current subset subset to the result res.
In the recursive case:
Include the current element nums[i] in the current subset subset.
Call the DFS function with the same index i + 1.
Remove the last element from the current subset to backtrack.
Move to the next index i + 1 without including the current element.
Call DFS:

Call the DFS function with an initial index of 0.
Remove Duplicates:

Convert the list of lists res to a set of tuples to remove duplicate subsets.
Convert the set of tuples back to a list of lists.
Return Result:

Return the final result result.

Complexity

  • Time complexity:

The time complexity is O(2^n), where n is the length of the array nums. This is because each element has two choices (include or exclude) for each recursive call, leading to 2^n possible subsets.

  • Space complexity:

The space complexity is O(n) due to the recursion stack. Additionally, the space required for the subset list contributes to the space complexity. The result res contains subsets, each with an average length of n/2, resulting in a space complexity of O(n * 2^n). The space for the temporary set is O(2^n).

Code

class Solution:
    def subsetsWithDup(self, nums):
        nums = sorted(nums)
        res = []
        subset = []

        def dfs(i):
            if i>= len(nums):
                res.append(subset.copy())
                return

            subset.append(nums[i])
            dfs(i + 1)

            subset.pop()
            dfs(i + 1)

        dfs(0)
        temp = set(tuple(inner_list) for inner_list in res)
        result = [list(t) for t in temp]
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值