
Sponsored
Sponsored
In this approach, the problem of subsets with duplicates is solved by first sorting the array. This assists in easily identifying and omitting duplicates. The backtracking method is utilized to construct all possible subsets, ensuring no duplicate subsets are generated by skipping duplicate numbers during recursive backtracking.
The time complexity of this solution is O(2^n * n) due to the number of subsets (2^n) and time taken to convert each subset to the result. The space complexity is O(n), where n is the length of the array, due to the space required for the subset building.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5class Solution {
6public:
7 void backtrack(std::vector<int>& nums, std::vector<std::vector<int>>& ans, std::vector<int>& current, int start) {
8 ans.push_back(current);
9 for (int i = start; i < nums.size(); ++i) {
10 if (i > start && nums[i] == nums[i - 1]) continue;
11 current.push_back(nums[i]);
12 backtrack(nums, ans, current, i + 1);
13 current.pop_back();
14 }
15 }
16 std::vector<std::vector<int>> subsetsWithDup(std::vector<int>& nums) {
17 std::sort(nums.begin(), nums.end());
18 std::vector<std::vector<int>> ans;
19 std::vector<int> current;
20 backtrack(nums, ans, current, 0);
21 return ans;
22 }
23};
24
25int main() {
26 Solution solution;
27 std::vector<int> nums = {1, 2, 2};
28 std::vector<std::vector<int>> result = solution.subsetsWithDup(nums);
29 for (const auto& subset : result) {
30 std::cout << "[";
31 for (size_t i = 0; i < subset.size(); ++i) {
32 std::cout << subset[i] << (i + 1 < subset.size() ? ", " : "");
33 }
34 std::cout << "]\n";
35 }
36 return 0;
37}Similar to the C solution, this C++ solution involves sorting the input array to manage duplicates better. It uses a recursive backtracking function to explore all unique subsets, avoiding duplicate subsets by skipping over duplicates during the backtracking process.
This approach iteratively constructs the power set by extending previously generated sets with each new number. During the process, duplicates are skipped by comparing the current number with the previous one. This ensures subsets generated in each iteration are unique.
The time complexity is O(2^n * n); space is O(2^n * n) as it iteratively builds the power set using subsets directly.
1#
The C solution utilizes iterative sets through a sorted array. It dynamically expands the subsets using the current number while bypassing duplicates by monitoring the indices of additions, skipping similar additions through index boundaries.