Skip to content

Commit 50f8904

Browse files
authored
Update 60-permutation-sequence.js
1 parent cda02c0 commit 50f8904

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

60-permutation-sequence.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,36 @@ const getPermutation = function(n, k) {
6262

6363
// another
6464

65+
/**
66+
* @param {number} n
67+
* @param {number} k
68+
* @return {string}
69+
*/
70+
const getPermutation = function(n, k) {
71+
const fact = []
72+
const nums = []
73+
for(let i = 1; i <= n; i++) {
74+
nums.push(i)
75+
}
76+
fact[0] = 1
77+
for(let i = 1, tmp = 1; i <= n; i++) {
78+
tmp *= i
79+
fact[i] = tmp
80+
}
81+
let res = ''
82+
k--
83+
for(let i = 1; i <= n; i++) {
84+
const idx = ~~(k / fact[n - i])
85+
res += nums[idx]
86+
nums.splice(idx, 1)
87+
k -= idx * fact[n - i]
88+
}
89+
90+
return res
91+
};
92+
93+
// another
94+
6595
/**
6696
* @param {number} n
6797
* @param {number} k

0 commit comments

Comments
 (0)