- Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathPermutationsII.java
More file actions
Latest commit
47 lines (43 loc) · 1.22 KB
/
Copy pathPermutationsII.java
File metadata and controls
47 lines (43 loc) · 1.22 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
importjava.util.ArrayList;
/**
* Given a collection of numbers that might contain duplicates, return all possible unique
* permutations.
*
* <p>For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1].
*/
publicclassPermutationsII {
publicArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> result = newArrayList<ArrayList<Integer>>();
permuteUnique(num, 0, result);
returnresult;
}
voidpermuteUnique(int[] num, intbegin, ArrayList<ArrayList<Integer>> result) {
if (begin > num.length - 1) {
ArrayList<Integer> item = newArrayList<Integer>();
for (inth = 0; h < num.length; h++) {
item.add(num[h]);
}
result.add(item);
}
for (intend = begin; end < num.length; end++) {
if (isSwap(num, begin, end)) {
swap(num, begin, end);
permuteUnique(num, begin + 1, result);
swap(num, begin, end);
}
}
}
booleanisSwap(int[] arr, inti, intj) {
for (intk = i; k < j; k++) {
if (arr[k] == arr[j]) {
returnfalse;
}
}
returntrue;
}
privatevoidswap(int[] a, inti, intj) {
inttmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}