-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_47_PermutationsII.java
66 lines (59 loc) · 1.72 KB
/
LeetCode_47_PermutationsII.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package problems.backtracking;
import java.util.*;
/**
* 47. 全排列 II
* 难度:中等
* 题目描述
* 给定一个可包含重复数字的序列,返回所有不重复的全排列。
*
* 示例:
* 输入: [1,1,2]
* 输出:
* [
* [1,1,2],
* [1,2,1],
* [2,1,1]
* ]
*
* @author kyan
* @date 2020/2/23
*/
public class LeetCode_47_PermutationsII {
/**
* 4 ms, 44.05%
* 41.2 MB, 18.12%
*/
public static class Solution1 {
private List<List<Integer>> res = new ArrayList<>();
private Map<Integer, Integer> countMap = new HashMap<>();
private Set<Integer> numSet = new HashSet<>();
private int N;
public List<List<Integer>> permuteUnique(int[] nums) {
for (int i = 0; i < nums.length; i++) {
countMap.put(nums[i], countMap.getOrDefault(nums[i], 0) + 1);
numSet.add(nums[i]);
}
N = nums.length;
backtrack(numSet, new ArrayList<>());
return res;
}
private void backtrack(Set<Integer> set, List<Integer> tmp) {
if (tmp.size() == N) {
res.add(new ArrayList<>(tmp));
return;
}
for (Integer num : set) {
if (countMap.get(num) == 0) continue;
countMap.put(num, countMap.get(num) - 1);
tmp.add(num);
backtrack(set, tmp);
countMap.put(num, countMap.get(num) + 1);
tmp.remove(tmp.size() - 1);
}
}
}
public static void main(String[] args) {
int[] nums = {1,1,2}; //[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
System.out.println(new Solution1().permuteUnique(nums));
}
}