-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path388.h
More file actions
48 lines (43 loc) · 1.07 KB
/
388.h
File metadata and controls
48 lines (43 loc) · 1.07 KB
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
44
45
46
47
48
class Solution {
public:
/*
* @param n: n
* @param k: the k th permutation
* @return: return the k-th permutation
*/
string getPermutation(int n, int k) {
// write your code here
string res = "";
k -= 1;
bool used[9];
for(int i = 0; i<n; i++)
used[i] = false;
while(true){
if(res.size() == n) break;
int p = fac(n-res.size()-1);
int index = k / p ;
if(k >= p){
k %= p;
}
for(int i = 0; i < n; i++){
if(!used[i]){
if(index == 0){
used[i] = true;
res += char(i + 1 + '0');
break;
}
else{
--index;
}
}
}
}
return res;
}
long long fac(int i){
long long r = 1;
while(i > 0)
r *= i--;
return r;
}
};