-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutationii.java
More file actions
32 lines (24 loc) · 972 Bytes
/
permutationii.java
File metadata and controls
32 lines (24 loc) · 972 Bytes
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
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
backtrack(nums, visited, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, boolean[] visited, List<Integer> temp, List<List<Integer>> result) {
if (temp.size() == nums.length) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) continue;
if (i > 0 && nums[i] == nums[i-1] && !visited[i-1]) continue;
visited[i] = true;
temp.add(nums[i]);
backtrack(nums, visited, temp, result);
visited[i] = false;
temp.remove(temp.size() - 1);
}
}
}