-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerset2.java
More file actions
45 lines (38 loc) · 1.4 KB
/
powerset2.java
File metadata and controls
45 lines (38 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class powerset2 {
public static void main(String[] args) {
int nums[]= {1,2,2};
System.out.println(subsetsWithDup(nums));
}
public static List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
findSubsets(nums,list,new ArrayList<>(),0);
return removeDuplicateSubsets(list);
}
public static void findSubsets(int[] nums,List<List<Integer>> list,ArrayList<Integer> temp,int i)
{
if(i>=nums.length){
list.add(new ArrayList<>(temp));
return;
}
findSubsets(nums,list,temp,i+1);
temp.add(nums[i]);
findSubsets(nums,list,temp,i+1);
temp.remove(temp.size()-1);
}
public static List<List<Integer>> removeDuplicateSubsets(List<List<Integer>> originalList) {
List<List<Integer>> uniqueSubsets = new ArrayList<>();
HashSet<List<Integer>> seenSubsets = new HashSet<>();
for (List<Integer> subset : originalList) {
// Sort the subset to make it comparable
subset.sort(null);
// Check if the subset has been seen before
if (seenSubsets.add(subset)) {
uniqueSubsets.add(subset);
}
}
return uniqueSubsets;
}
}