forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations2.java
More file actions
72 lines (65 loc) · 2.44 KB
/
Copy pathPermutations2.java
File metadata and controls
72 lines (65 loc) · 2.44 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
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
/*
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
*/
// DFS, O(n!)
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (num==null || num.length==0) return res;
Arrays.sort(num); // Remember to sort here
boolean[] visited = new boolean[num.length];
finder(num, 0, res, new ArrayList<Integer>(), visited);
return res;
}
public void finder(int[] num, int len, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> r, boolean[] visited){
if (len == num.length){
res.add(new ArrayList<Integer>(r));
return;
}
Set<Integer> visited_val = new HashSet<Integer>(); // to avoid using duplicate values in one loop
for (int i=0; i<num.length; i++){
if (visited_val.contains(num[i]) || visited[i]) continue;
r.add(num[i]);
visited[i] = true;
visited_val.add(num[i]);
finder(num, len+1, res, r, visited);
r.remove(r.size()-1);
visited[i] = false;
}
}
}
// In place swap, swap different values to current position
// if same value is encountered, skip it
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);
perm(num, 0, res);
return res;
}
private void perm(int[] num, int index, ArrayList<ArrayList<Integer>> res){
if (index==num.length){
ArrayList<Integer> r = new ArrayList<Integer>();
for (int val:num) r.add(val);
res.add(r);
return;
}
Set<Integer> set = new HashSet<Integer>();
for (int i=index; i<num.length; i++){
if (set.contains(num[i])) // avoid same value
continue;
swap(num, index, i);
perm(num, index+1, res); // Note: index+1, not i+1
swap(num, index, i);
set.add(num[i]);
}
}
private void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}