-
Notifications
You must be signed in to change notification settings - Fork 156
/
Permutation_Sequence.cpp
52 lines (38 loc) · 980 Bytes
/
Permutation_Sequence.cpp
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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums;
int fact = 1;
for(int i = 1; i < n; i++)
{
fact = fact * i;
nums.push_back(i);
}
nums.push_back(n);
string ans = "";
k = k - 1;
while(true)
{
ans = ans + to_string(nums[k / fact]);
nums.erase(nums.begin() + k / fact);
if(nums.size() == 0)
break;
k = k % fact;
fact = fact / nums.size();
}
return ans;
}
};
int main()
{
int n, k;
cout<<"Enter a number here :- ";
cin>>n;
cout<<"Enter the value of K :- ";
cin>>k;
Solution obj;
string ans = obj.getPermutation(n, k);
cout<<k<<"th Permutation Sequence of given number "<<n<<"is :- "<<ans;
}