-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Kth permutation
57 lines (49 loc) · 941 Bytes
/
Find Kth permutation
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
49
50
51
52
53
54
55
56
57
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
string kthPermutation(int n, int k)
{
// code here
string h="";
int chk=1;
for(int i=1;i<=n;i++){
h+=to_string(i);
chk*=i;
}
string ans="";
int i=0,g=0,r=0;
while(i<n){
r=chk/(n-i),g=k/r;
if(k%r==0) g--;
ans+=h[g];
h.erase(h.begin()+g);
k=k-(r)*(g);
i++;
chk=r;
}
return ans;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
Solution ob;
string ans = ob.kthPermutation(n, k);
cout << ans;
cout << "\n";
}
return 0;
}
// } Driver Code Ends