Skip to content

Commit 5b6b238

Browse files
authored
Update 60-permutation-sequence.js
1 parent 76cd794 commit 5b6b238

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

60-permutation-sequence.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,31 @@
1+
/**
2+
* @param {number} n
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
const getPermutation = function(n, k) {
7+
const factorial = Array(n + 1).fill(0)
8+
factorial[0] = 1
9+
for(let i = 1, pre = 1; i <= n; i++) {
10+
factorial[i] = pre * i
11+
pre = factorial[i]
12+
}
13+
const nums = Array.from({length: n}, (_, i) => i + 1)
14+
15+
let res = ''
16+
k--
17+
for(let i = 1; i <= n; i++) {
18+
const idx = ~~(k / factorial[n - i])
19+
res += nums[idx]
20+
nums.splice(idx, 1)
21+
k -= idx * factorial[n - i]
22+
}
23+
24+
return res
25+
};
26+
27+
// another
28+
129
/**
230
* @param {number} n
331
* @param {number} k

0 commit comments

Comments
 (0)