-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPermuteUnique.java
47 lines (41 loc) · 1.44 KB
/
PermuteUnique.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package ds.backtrack;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* 全排列II
* LeetCode 47 https://leetcode-cn.com/problems/permutations-ii/
*
* @author yangyi 2021年01月05日14:58:34
*/
public class PermuteUnique {
private final List<List<Integer>> result = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
backtrack(nums, new LinkedList<>(), new HashMap<>());
return result;
}
private void backtrack(int[] nums, LinkedList<Integer> track, HashMap<Integer, Boolean> used) {
if (nums.length == track.size()) {
result.add(new LinkedList<>(track));
return;
}
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i] && !used.getOrDefault(i - 1, false)) {
continue;
}
if (!used.getOrDefault(i, false)) {
used.put(i, true);
track.add(nums[i]);
backtrack(nums, track, used);
track.removeLast();
used.put(i, false);
}
}
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new PermuteUnique().permuteUnique(new int[]{1, 1, 2}).toArray()));
System.out.println(Arrays.toString(new PermuteUnique().permuteUnique(new int[]{1, 2, 3}).toArray()));
}
}