-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPermutation ii.java
More file actions
48 lines (43 loc) · 1.54 KB
/
Permutation ii.java
File metadata and controls
48 lines (43 loc) · 1.54 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
/*
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].
*/
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permuteUnique(num, 0, result);
return result;
}
public void permuteUnique(int[] num, int begin, ArrayList<ArrayList<Integer>> result) {
if (begin == num.length) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int h = 0; h < num.length; h++) {
list.add(num[h]);
}
result.add(list);
}
for (int end = begin; end < num.length; end++) {
if (isSwap(num, begin, end)) {
int temp = num[end];
num[end] = num[begin];
num[begin] = temp;
permuteUnique(num, begin + 1, result);
temp = num[end];
num[end] = num[begin];
num[begin] = temp;
}
}
}
public boolean isSwap(int[] arr, int i, int j) {
for (int k = i; k < j; k++) {
if (arr[k] == arr[j]) {
return false;
}
}
return true;
}
}