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. Let's explore some examples.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
Can you provide an algorithm to solve this problem efficiently, considering the constraints and the need to avoid duplicate subsets?
The most straightforward approach is to generate all possible subsets without considering duplicates initially and then remove the duplicate subsets at the end.
nums
. This can be achieved using nested loops or recursion.nums
. Additionally, removing duplicates can take O(M2) where M = 2N in the worst case, leading to a combined complexity of O(N * 2N + M2). The actual complexity of removing duplicates depends on the data structure used and the method applied. In the worst case, M == 2N, so O(22N) for duplicate removals.def subsets_with_duplicates_brute_force(nums):
subsets = []
for i in range(1 << len(nums)):
subset = []
for j in range(len(nums)):
if (i >> j) & 1:
subset.append(nums[j])
subsets.append(subset)
unique_subsets = []
for subset in subsets:
subset.sort()
if subset not in unique_subsets:
unique_subsets.append(subset)
return unique_subsets
# Example Usage
nums = [1, 2, 2]
result = subsets_with_duplicates_brute_force(nums)
print(result)
A more efficient approach is to use backtracking. The key optimization here is to avoid generating duplicate subsets during the backtracking process itself. This is typically done by sorting the input array and skipping over duplicate elements during the recursive calls.
def subsets_with_duplicates_optimal(nums):
result = []
nums.sort()
def backtrack(index, subset):
result.append(subset[:]) # Append a copy of the subset
for i in range(index, len(nums)):
# Skip duplicate numbers
if i > index and nums[i] == nums[i - 1]:
continue
subset.append(nums[i])
backtrack(i + 1, subset)
subset.pop() # Backtrack: remove the last element
backtrack(0, [])
return result
# Example Usage
nums = [1, 2, 2]
result = subsets_with_duplicates_optimal(nums)
print(result)