-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDuplicateSubset.java
More file actions
35 lines (31 loc) · 1.35 KB
/
DuplicateSubset.java
File metadata and controls
35 lines (31 loc) · 1.35 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
import java.util.*;
class DuplicateSubset {
public static List<List<Integer>> findSubsets(int[] nums) {
// sort the numbers to handle duplicates
Arrays.sort(nums);
List<List<Integer>> subsets = new ArrayList<>();
subsets.add(new ArrayList<>());
int startIndex = 0, endIndex = 0;
for (int i = 0; i < nums.length; i++) {
startIndex = 0;
// if current and the previous elements are same, create new subsets only from the subsets
// added in the previous step
if (i > 0 && nums[i] == nums[i - 1])
startIndex = endIndex + 1;
endIndex = subsets.size() - 1;
for (int j = startIndex; j <= endIndex; j++) {
// create a new subset from the existing subset and add the current element to it
List<Integer> set = new ArrayList<>(subsets.get(j));
set.add(nums[i]);
subsets.add(set);
}
}
return subsets;
}
public static void main(String[] args) {
List<List<Integer>> result = DuplicateSubset.findSubsets(new int[] { 1, 3, 3 });
System.out.println("Here is the list of subsets: " + result);
result = DuplicateSubset.findSubsets(new int[] { 1, 5, 3, 3 });
System.out.println("Here is the list of subsets: " + result);
}
}