Skip to content

Commit dddab44

Browse files
committedJan 3, 2025
Add solution #60
1 parent 2487ec2 commit dddab44

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
57|[Insert Interval](./0057-insert-interval.js)|Medium|
6666
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
6767
59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium|
68+
60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard|
6869
62|[Unique Paths](./0062-unique-paths.js)|Medium|
6970
64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium|
7071
66|[Plus One](./0066-plus-one.js)|Easy|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 60. Permutation Sequence
3+
* https://leetcode.com/problems/permutation-sequence/
4+
* Difficulty: Hard
5+
*
6+
* The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
7+
*
8+
* By listing and labeling all of the permutations in order, we get the
9+
* following sequence for n = 3:
10+
* - "123"
11+
* - "132"
12+
* - "213"
13+
* - "231"
14+
* - "312"
15+
* - "321"
16+
*
17+
* Given n and k, return the kth permutation sequence.
18+
*/
19+
20+
/**
21+
* @param {number} n
22+
* @param {number} k
23+
* @return {string}
24+
*/
25+
var getPermutation = function(n, k) {
26+
const factorial = [1];
27+
for (let i = 1; i < n; i++) {
28+
factorial[i] = factorial[i-1] * i;
29+
}
30+
31+
const values = new Array(n).fill(0).map((_, i) => i + 1);
32+
let result = '';
33+
k--;
34+
35+
for (let i = n - 1; i >= 0; i--) {
36+
const index = Math.floor(k / factorial[i]);
37+
k = k % factorial[i];
38+
result += values[index];
39+
values.splice(index, 1);
40+
}
41+
42+
return result;
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.