-
Notifications
You must be signed in to change notification settings - Fork 257
/
permutation-index-ii.cpp
108 lines (104 loc) · 3.19 KB
/
permutation-index-ii.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
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
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndexII(vector<int>& A) {
long long index = 1;
// Position 1 is paired with factor 0 and so is skipped.
int position = 2;
long long factor = 1;
map<int, int> number_to_count;
++number_to_count[A.back()];
for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {
++number_to_count[A[i]];
for (const auto& kvp : number_to_count) {
if (kvp.first >= A[i]) {
break;
}
index += factor * kvp.second / number_to_count[A[i]];
}
factor = factor * position / number_to_count[A[i]];
++position;
}
return index;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndexII(vector<int>& A) {
long long index = 1;
// Position 1 is paired with factor 0 and so is skipped.
int position = 2;
long long factor = 1;
unordered_map<int, int> number_to_count;
++number_to_count[A.back()];
for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {
unordered_map<int, int> successor_to_count;
++number_to_count[A[i]];
for (int j = i + 1; j < A.size(); ++j) {
if (A[i] > A[j]) {
++successor_to_count[A[j]];
}
}
for (const auto& kvp : successor_to_count) {
index += factor * kvp.second / number_to_count[A[i]];
}
factor = factor * position / number_to_count[A[i]];
++position;
}
return index;
}
};
// Time: O(n^3)
// Space: O(n)
class Solution3 {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndexII(vector<int>& A) {
long long index = 1;
unordered_map<int, int> number_to_count;
++number_to_count[A.back()];
for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {
unordered_map<int, int> successor_to_count;
++number_to_count[A[i]];
for (int j = i + 1; j < A.size(); ++j) {
if (A[i] > A[j]) {
++successor_to_count[A[j]];
}
}
for (const auto& kvp : successor_to_count) {
--number_to_count[kvp.first];
index += combination(number_to_count);
++number_to_count[kvp.first];
}
}
return index;
}
long long combination(const unordered_map<int, int>& number_to_count) {
int n = 0;
for (const auto& kvp : number_to_count) {
n += kvp.second;
}
long long count = 1;
for (const auto& kvp : number_to_count) {
// C(n, k) = (n) / 1 * (n - 1) / 2 ... * (n - k + 1) / k
for (int i = 1; i <= kvp.second; ++i, --n) {
count = count * n / i;
}
}
return count;
}
};