-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1569.cpp
More file actions
executable file
·60 lines (51 loc) · 1.25 KB
/
LC1569.cpp
File metadata and controls
executable file
·60 lines (51 loc) · 1.25 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
/*
Problem Statement: https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/
Time: O(n²)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
private:
const int mod = 1e9 + 7;
vector<int64_t> fact, inv_fact;
public:
int numOfWays(vector<int>& nums) {
int n = nums.size(), m = 2 * n;
fact = vector<int64_t>(m + 1);
inv_fact = vector<int64_t>(m + 1);
// precompute the factorials & inverse factorials
fact[0] = 1;
for (int i = 1; i <= m; i++)
fact[i] = i * fact[i - 1] % mod;
inv_fact[m] = mod_power(fact[m], mod - 2);
for (int i = m - 1; i >= 0; i--)
inv_fact[i] = (i + 1) * inv_fact[i + 1] % mod;
return dfs(nums) - 1;
}
int mod_power(int64_t x, int n) {
int y = 1;
while (n) {
if (n & 1)
y = (y * x) % mod;
n >>= 1;
x = (x * x) % mod;
}
return y;
}
int nCr(int n, int r) {
return (fact[n] * inv_fact[n - r] % mod) * inv_fact[r] % mod;
}
int64_t dfs(vector<int>& nums) {
int n = nums.size();
vector<int> l, r;
if (n <= 1)
return 1;
for (int i = 1; i < n; i++) {
if (nums[i] < nums[0])
l.push_back(nums[i]);
else
r.push_back(nums[i]);
}
return (dfs(l) * dfs(r) % mod) * nCr(l.size() + r.size(), r.size()) % mod;
}
};