-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path0060-permutation-sequence.js
More file actions
43 lines (39 loc) · 910 Bytes
/
0060-permutation-sequence.js
File metadata and controls
43 lines (39 loc) · 910 Bytes
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
/**
* 60. Permutation Sequence
* https://leetcode.com/problems/permutation-sequence/
* Difficulty: Hard
*
* The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
*
* By listing and labeling all of the permutations in order, we get the
* following sequence for n = 3:
* - "123"
* - "132"
* - "213"
* - "231"
* - "312"
* - "321"
*
* Given n and k, return the kth permutation sequence.
*/
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
const factorial = [1];
for (let i = 1; i < n; i++) {
factorial[i] = factorial[i-1] * i;
}
const values = new Array(n).fill(0).map((_, i) => i + 1);
let result = '';
k--;
for (let i = n - 1; i >= 0; i--) {
const index = Math.floor(k / factorial[i]);
k = k % factorial[i];
result += values[index];
values.splice(index, 1);
}
return result;
};