-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetPermutation.cpp
More file actions
executable file
·51 lines (44 loc) · 1.08 KB
/
getPermutation.cpp
File metadata and controls
executable file
·51 lines (44 loc) · 1.08 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
49
50
51
/*
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
1 "123"
2 "132"
3 "213"
4 "231"
5 "312"
6 "321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
*/
#include <vector>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int getPermutation(int n, int k){
int out = 0;
int tp = 1;
std::vector<int> vint(n,0);
for(int i = 1; i <=n; ++i){
tp *= i;
vint[i-1] = i;
//cout << " " << vint[i];
}
k = k - 1;
for(int ct = 0; ct < n; ++ct){
tp = tp/(n - ct);
int id = k/tp;
//cout << tp << " " << out << " " << vint[id] << " " << id << endl;
out = out*10 + vint[id];
//out += string(itoa(v[id]);
vint.erase(vint.begin() + id);
k -= id*tp;
}
return out;
}
int main(int argc, char const *argv[])
{
cout << getPermutation(4,11) << endl;
return 0;
}