
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.
1using System;
2using System.Collections.Generic;
3
4class Solution {
5 public IList<IList<int>> SubsetsWithDup(int[] nums) {
6 Array.Sort(nums);
7 IList<IList<int>> result = new List<IList<int>>();
8 Backtrack(result, new List<int>(), nums, 0);
9 return result;
10 }
11
12 private void Backtrack(IList<IList<int>> result, IList<int> tempList, int[] nums, int start) {
13 result.Add(new List<int>(tempList));
14 for (int i = start; i < nums.Length; i++) {
15 if (i > start && nums[i] == nums[i - 1]) continue;
16 tempList.Add(nums[i]);
17 Backtrack(result, tempList, nums, i + 1);
18 tempList.RemoveAt(tempList.Count - 1);
19 }
20 }
21
22 public static void Main(string[] args) {
23 Solution solution = new Solution();
24 var result = solution.SubsetsWithDup(new int[] { 1, 2, 2 });
25 foreach (var subset in result) {
26 Console.WriteLine("[" + string.Join(", ", subset) + "]");
27 }
28 }
29}This C# solution leverages the same sorting and backtracking strategy. A helper method recursively generates unique subsets by preventing the use of duplicates in any recursion step.
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.