-
Notifications
You must be signed in to change notification settings - Fork 20
/
PermutationsII.js
70 lines (61 loc) · 1.44 KB
/
PermutationsII.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
*
* For example,
* [1,1,2] have the following unique permutations:
* [
* [1,1,2],
* [1,2,1],
* [2,1,1]
* ]
*
* Accepted.
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
let permuteUnique = function (nums) {
let results = [];
if (nums.length === 0) {
return results;
}
if (nums.length === 1) {
results.push([nums[0]]);
return results;
}
let ints = [];
for (let i = 0; i < nums.length - 1; i++) {
ints[i] = nums[i];
}
let map = new Map();
permuteUnique(ints).forEach(function (list) {
for (let i = 0; i < list.length; i++) {
let tmp = [];
list.forEach(function (element) {
tmp.push(element);
});
tmp.splice(i, 0, nums[nums.length - 1]);
map.set(tmp.toString(), tmp);
}
});
map.forEach(function (value, key, map) {
results.push(value);
});
return results
};
if (permuteUnique([]).length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (permuteUnique([1]).toString() === [[1]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (new Set(permuteUnique([1, 1, 2])).toString() === new Set([[1, 1, 2], [1, 2, 1], [2, 1, 1]]).toString()) {
console.log("pass")
} else {
console.error("failed")
}