Skip to content

Commit 815f244

Browse files
authored
Update 60-permutation-sequence.js
1 parent 5b6b238 commit 815f244

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

60-permutation-sequence.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,39 @@
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; i <= n; i++) {
10+
factorial[i] = factorial[i - 1] * i
11+
}
12+
let res = ''
13+
const visited = Array(n + 1).fill(0)
14+
dfs(0)
15+
return res
16+
17+
function dfs(idx) {
18+
if(idx === n) return
19+
20+
const cnt = factorial[n - idx - 1]
21+
for(let i = 1; i <= n; i++) {
22+
if(visited[i]) continue
23+
if(cnt < k) {
24+
k -= cnt
25+
continue
26+
}
27+
res += i
28+
visited[i] = 1
29+
dfs(idx + 1)
30+
return
31+
}
32+
}
33+
};
34+
35+
// another
36+
137
/**
238
* @param {number} n
339
* @param {number} k

0 commit comments

Comments
 (0)