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.
nums
array?nums
is empty?Assuming the answers are:
nums
array will be bounded, say up to 10^4
.nums
is empty, return [[]]
.nums
array to handle duplicates easily.Here is the C++ code to solve the problem:
#include <vector>
#include <algorithm>
class Solution {
public:
void backtrack(int start, std::vector<int>& nums, std::vector<int>& current, std::vector<std::vector<int>>& result) {
result.push_back(current);
for (int i = start; i < nums.size(); ++i) {
if (i > start && nums[i] == nums[i - 1]) continue; // Skip duplicates
current.push_back(nums[i]);
backtrack(i + 1, nums, current, result);
current.pop_back();
}
}
std::vector<std::vector<int>> subsetsWithDup(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end()); // Sort to handle duplicates
std::vector<std::vector<int>> result;
std::vector<int> current;
backtrack(0, nums, current, result);
return result;
}
};
nums
array.Therefore, the overall time complexity is O(n log n) + O(n * 2^n) ≈ O(n * 2^n).
This approach ensures that we handle duplicates correctly and generates all unique subsets efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?