-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
48 lines (39 loc) · 1.3 KB
/
res.ts
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
function getUniqueList(numsCountMap: { [key in number]: number }): number[][] {
const result: number[][] = [];
const keys = Object.keys(numsCountMap);
keys.forEach((key) => {
// @ts-ignore
const currentCount = numsCountMap[key];
const currentNum = Number(key);
if (currentCount) {
const newNumsCountMap = { ...numsCountMap };
// @ts-ignore
newNumsCountMap[key]--;
for (let newKey in newNumsCountMap) {
if (!newNumsCountMap[newKey]) {
delete newNumsCountMap[newKey];
}
}
const uniqueList = getUniqueList(newNumsCountMap);
if (!uniqueList.length) {
result.push([currentNum]);
} else {
uniqueList.forEach((item) => {
result.push([currentNum, ...item]);
});
}
}
})
return result;
}
function permuteUnique(nums: number[]): number[][] {
const numsCountMap: { [key in number]: number } = {};
nums.sort((a, b) => a - b);
nums.forEach((num, index) => {
numsCountMap[num] = numsCountMap[num] ? numsCountMap[num] + 1 : 1;
});
if (nums.length <= 1) {
return [nums];
}
return getUniqueList(numsCountMap);
};