forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_90.java
80 lines (73 loc) · 2.65 KB
/
_90.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _90 {
public static class Solution1 {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList();
List<Integer> empty = new ArrayList();
result.add(empty);
if (nums == null) {
return result;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
Set<List<Integer>> temp = new HashSet();
for (List<Integer> list : result) {
List<Integer> newList = new ArrayList(list);
newList.add(nums[i]);
temp.add(newList);
}
result.addAll(temp);
}
Set<List<Integer>> resultSet = new HashSet();
resultSet.addAll(result);
result.clear();
result.addAll(resultSet);
return result;
}
}
public static class Solution2 {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList();
Arrays.sort(nums);
backtrack(nums, 0, new ArrayList(), result);
return result;
}
void backtrack(int[] nums, int start, List<Integer> curr, List<List<Integer>> result) {
result.add(new ArrayList(curr));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
curr.add(nums[i]);
backtrack(nums, i + 1, curr, result);
curr.remove(curr.size() - 1);
}
}
}
public static class Solution3 {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
result.add(list);
Arrays.sort(nums);
backtracking(nums, 0, result, list);
return result;
}
private void backtracking(int[] nums, int start, List<List<Integer>> result, List<Integer> list) {
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
list.add(nums[i]);
result.add(new ArrayList<>(list));
backtracking(nums, i + 1, result, list);
list.remove(list.size() - 1);
}
}
}
}