-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutation_sequence.cpp
More file actions
125 lines (98 loc) · 2.58 KB
/
Copy pathpermutation_sequence.cpp
File metadata and controls
125 lines (98 loc) · 2.58 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
Permutation Sequence
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):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// TLE
class Solution
{
public:
string getPermutation(int n, int k)
{
string ret;
if (k <= 0)
return ret;
vector<int> v(n);
iota(v.begin(), v.end(), 1);
while (--k) {
next_permutation(v.begin(), v.end());
}
for (auto t : v) {
ret += t + '0';
}
return ret;
}
};
/*
X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[2]*1!+a[1]*0!
a is integer, and 0<=a[i]<i(1<=i<=n)
this equation maps a natural number
i.e:,3 5 7 4 1 2 9 6 8 maps 98884.
because X=2*8!+3*7!+4*6!+2*5!+0*4!+0*3!+2*2!+0*1!+0*0! = 98884.
why?
1) considering first number 3, so there are two numbers(1, 2) less than 3,
and permutation leading with them is 8!, so it is 2 * 8!
2) considering 5, there are four numbers(1, 2 ,3 , 4) less than it,
and 3 was used in the first item, so there remains 3 numbers usable.
that is 3 * 7!
Application:
Give a number(include digit 1...n), we can calculate its postion in permutation.
*/
class Solution2
{
public:
long long factorial(int n)
{
long long product = 1;
for (int i = 2; i <= n; i++) {
product *= i;
}
return product;
}
string getPermutation(int n, int k)
{
if (n < 1 || k < 1)
return "";
string orig(n, '0'), ret;
for (int i = 1; i <= n; i++) {
orig[i - 1] += i;
}
// Cantor encode, minus one to start from 0
// because we will use %
--k;
int base = factorial(n - 1); // (n-1)!
for (int i = n - 1; i > 0; k %= base, base /= i, --i) {
// judge it belongs to which permutation
// the sub permu, leading with orig[sub]
int sub = k / base;
ret += orig[sub];
orig.erase(sub, 1);
}
ret += orig[0]; // i == 0, the last one
return ret;
}
};
int main(int argc, char *argv[])
{
Solution sol;
Solution2 sol2;
for (int i = 1; i <= 6; i++) {
cout << sol.getPermutation(3, i) << endl;
cout << sol2.getPermutation(3, i) << endl;
}
return 0;
}