Skip to content

Commit d06e68b

Browse files
committed
Create Permutations II.java
1 parent 15a012f commit d06e68b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Algorithms/Permutations II.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class Solution {
2+
public List<List<Integer>> permuteUnique(int[] num) {
3+
List<List<Integer>> result = new ArrayList<List<Integer>>();
4+
if (num.length == 0) return result;
5+
boolean[] used = new boolean[num.length];
6+
List<Integer> list = new ArrayList<Integer>();
7+
Arrays.sort(num);
8+
dfs(num, num.length, list, used, result);
9+
return result;
10+
}
11+
12+
private void dfs(int[] num, int n, List<Integer> list, boolean[] used, List<List<Integer>> result) {
13+
if (list.size() == n) {
14+
result.add(new ArrayList<Integer>(list));
15+
} else {
16+
for (int i = 0; i < n; i++) {
17+
if (used[i] == false) {
18+
used[i] = true;
19+
list.add(num[i]);
20+
dfs(num, n, list, used, result);
21+
used[i] = false;
22+
list.remove(list.size() - 1);
23+
while (i < n - 1 && num[i] == num[i+1]) i++;
24+
}
25+
}
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)