Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
52 lines (45 loc) · 1.16 KB

File metadata and controls

52 lines (45 loc) · 1.16 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import java.util.ArrayList;
/**
* 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 PermutationsII {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permuteUnique(num, 0, result);
return result;
}
void permuteUnique(int[] num, int begin,
ArrayList<ArrayList<Integer>> result) {
if (begin > num.length - 1) {
ArrayList<Integer> item = new ArrayList<Integer>();
for (int h = 0; h < num.length; h++) {
item.add(num[h]);
}
result.add(item);
}
for (int end = begin; end < num.length; end++) {
if (isSwap(num, begin, end)) {
swap(num, begin, end);
permuteUnique(num, begin + 1, result);
swap(num, begin, end);
}
}
}
boolean isSwap(int[] arr, int i, int j) {
for (int k = i; k < j; k++) {
if (arr[k] == arr[j]) {
return false;
}
}
return true;
}
private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.