Here's a code in C++ that uses recursion to find all unique subsets of an array with duplicate elements:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void findUniqueSubsets(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& subsets) {
// Add the current subset to the result
subsets.push_back(current);
for (int i = index; i < nums.size(); i++) {
// Skip duplicate elements
if (i > index && nums[i] == nums[i - 1])
continue;
// Include the current element in the subset
current.push_back(nums[i]);
// Recursively generate subsets with the remaining elements
findUniqueSubsets(nums, i + 1, current, subsets);
// Exclude the current element from the subset (backtrack)
current.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> subsets;
vector<int> current;
sort(nums.begin(), nums.end()); // Sort the array to handle duplicates
findUniqueSubsets(nums, 0, current, subsets);
return subsets;
}
int main() {
vector<int> nums = {1, 2, 2};
vector<vector<int>> result = subsetsWithDup(nums);
// Output the subsets
for (const auto& subset : result) {
cout << "[ ";
for (const auto& num : subset) {
cout << num << " ";
}
cout << "]" << endl;
}
return 0;
}
Output:
[ ]
[ 1 ]
[ 1 2 ]
[ 1 2 2 ]
[ 2 ]
[ 2 2 ]
Explanation:
The code utilizes recursion and backtracking to generate all unique subsets. The sorting step is crucial to handling duplicates, as it allows us to skip duplicate elements during the generation process.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|