-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubSet.java
50 lines (47 loc) · 1.51 KB
/
SubSet.java
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
46
47
48
49
50
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubSet {
public static void main(String[] args) {
int[] arr = {1, 2, 2};
List<List<Integer>> ans = subsetDuplicate(arr);
for (List<Integer> list : ans) {
System.out.println(list);
}
}
static List<List<Integer>> subset(int[] arr) {
List<List<Integer>> outer = new ArrayList<>();
outer.add(new ArrayList<>());
for (int num : arr) {
int n = outer.size();
for (int i = 0; i < n; i++) {
List<Integer> internal = new ArrayList<>(outer.get(i));
internal.add(num);
outer.add(internal);
}
}
return outer;
}
static List<List<Integer>> subsetDuplicate(int[] arr) {
Arrays.sort(arr);
List<List<Integer>> outer = new ArrayList<>();
outer.add(new ArrayList<>());
int start = 0;
int end = 0;
for (int i = 0; i < arr.length; i++) {
start = 0;
// if current and previous element is same, s = e + 1
if (i > 0 && arr[i] == arr[i-1]) {
start = end + 1;
}
end = outer.size() - 1;
int n = outer.size();
for (int j = start; j < n; j++) {
List<Integer> internal = new ArrayList<>(outer.get(j));
internal.add(arr[i]);
outer.add(internal);
}
}
return outer;
}
}