-
Notifications
You must be signed in to change notification settings - Fork 91
/
Permutations_II.js
48 lines (39 loc) · 908 Bytes
/
Permutations_II.js
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
/*
Permutations II
https://leetcode.com/problems/permutations-ii/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
var permuteUnique = function (nums) {
var map = {};
for (var i = 0; i < nums.length; i++) {
var value = nums[i];
map[value] = map[value] ? map[value] + 1 : 1;
}
return permuteUniqueAux(nums.length, map, []);
};
var permuteUniqueAux = function (n, map, currentSol) {
if (currentSol.length === n) {
return [currentSol];
}
var ret = [];
for (var num in map) {
const occ = map[num];
if (occ === 1) {
delete map[num];
} else {
map[num] = occ - 1;
}
ret = [...ret, ...permuteUniqueAux(n, map, currentSol.concat(num))];
map[num] = occ;
}
return ret;
};
module.exports.permuteUnique = permuteUnique;