-
Notifications
You must be signed in to change notification settings - Fork 115
/
060-PermutationSequence.cs
43 lines (37 loc) · 1.07 KB
/
060-PermutationSequence.cs
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
//-----------------------------------------------------------------------------
// Runtime: 80ms
// Memory Usage: 22.9 MB
// Link: https://leetcode.com/submissions/detail/356457712/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _060_PermutationSequence
{
public string GetPermutation(int n, int k)
{
var nums = new List<int>();
var group = 1;
for (int i = 1; i <= n; i++)
{
nums.Add(i);
group *= i;
}
if (k > group) return "";
k = k > 0 ? k - 1 : 0;
var result = new StringBuilder();
var index = -1;
while (n > 0)
{
group /= n;
index = k / group;
result.Append(nums[index]);
nums.RemoveAt(index);
k = k % group;
n--;
}
return result.ToString();
}
}
}