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

你可能感兴趣的:(leetcode算法学习,深度优先,算法)