File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 4 ms, faster than 69.49% of C++ online submissions for Permutation Sequence.
2
+ // Memory Usage: 8.1 MB, less than 98.28% of C++ online submissions for Permutation Sequence.
3
+
4
+ class Solution
5
+ {
6
+ public:
7
+ string getPermutation (int n, int k)
8
+ {
9
+ string res = " " ;
10
+ --k;
11
+
12
+ vector<char > candidate (n);
13
+ for (int i = 0 ; i < n; ++i)
14
+ candidate[i] = i + 1 ;
15
+
16
+ for (int i = 0 ; i < n - 1 ; ++i)
17
+ {
18
+ int fac = factorial (n - 1 - i);
19
+ int index = k / fac;
20
+
21
+ res += candidate[index ] + ' 1' - 1 ;
22
+ k %= fac;
23
+
24
+ vector<char >::iterator iter = candidate.begin () + index ;
25
+ candidate.erase (iter);
26
+ }
27
+ res += candidate[0 ] + ' 1' - 1 ;
28
+ return res;
29
+ }
30
+ private:
31
+
32
+ // 计算阶乘的小函数
33
+ int factorial (int n)
34
+ {
35
+ int res = 1 ;
36
+ for (int i = 1 ; i <= n; ++i)
37
+ res *= i;
38
+ return res;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments