-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
62 lines (56 loc) · 1.94 KB
/
Solution.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
// Solution without pruning
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] flags = new boolean[nums.length];
List<Integer> path = new ArrayList<>();
Set<List<Integer>> res = new HashSet<>();
Arrays.sort(nums);
dfs(nums, flags, path, res);
return new ArrayList<>(res);
}
public void dfs(int[] nums, boolean[] flags, List<Integer> path, Set<List<Integer>> res) {
if(path.size() == flags.length) {
res.add(List.copyOf(path));
return;
}
for(int idx = 0; idx < nums.length; idx++) {
if(!flags[idx]) {
flags[idx] = true;
path.add(nums[idx]);
dfs(nums, flags, path, res);
flags[idx] = false;
path.remove(path.size() - 1);
}
}
}
}
// Solution with pruning
// class Solution {
// public List<List<Integer>> permuteUnique(int[] nums) {
// boolean[] flags = new boolean[nums.length];
// List<Integer> path = new ArrayList<>();
// Set<List<Integer>> res = new HashSet<>();
// Arrays.sort(nums);
// dfs(nums, flags, path, res);
// return new ArrayList<>(res);
// }
// public void dfs(int[] nums, boolean[] flags, List<Integer> path, Set<List<Integer>> res) {
// if(path.size() == flags.length) {
// res.add(List.copyOf(path));
// return;
// }
// for(int idx = 0; idx < nums.length; idx++) {
// // pruning
// if(idx > 0 && nums[idx] == nums[idx - 1] && !flags[idx - 1]) {
// continue;
// }
// if(!flags[idx]) {
// flags[idx] = true;
// path.add(nums[idx]);
// dfs(nums, flags, path, res);
// flags[idx] = false;
// path.remove(path.size() - 1);
// }
// }
// }
// }