forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0047-permutations-ii.java
33 lines (27 loc) · 941 Bytes
/
0047-permutations-ii.java
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
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
backtrack(res, nums, new ArrayList<>(), new boolean[nums.length]);
return res;
}
public void backtrack(List<List<Integer>> res,
int[] nums,
List<Integer> path,
boolean[] visited) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] ||
(i > 0 && nums[i - 1] == nums[i] && visited[i - 1]))
continue;
visited[i] = true;
path.add(nums[i]);
backtrack(res, nums, path, visited);
visited[i] = false;
path.remove(path.size() - 1);
}
}
}