Problem Description
Given an integer array that may contain duplicates, return all possible subsets (the power set) without including duplicate subsets. The order of the subsets is not important.
Key Insights
- Sort the array first so that duplicate elements are adjacent.
- Use backtracking to generate all possible subsets.
- Skip duplicate elements in the recursion to avoid forming duplicate subsets.
- The use of sorted order and conditionally skipping elements is the trick to handle duplicates.
Space and Time Complexity
Time Complexity: O(2^n * n) since each subset creation may take O(n) in the worst case.
Space Complexity: O(2^n * n) for storing the subsets, plus O(n) for recursion stack.
Solution
The solution uses a backtracking technique that builds subsets incrementally. The input array is first sorted to bring duplicates together. During recursion, if the current element is the same as the previous one and it has not been used in the current recursion path, it is skipped to prevent duplicate subsets. This ensures that each subset is unique. The algorithm stores each valid subset by copying the current subset state into the result list.