Your task is to calculate the number of valid bracket sequences of length n. For example, when , there are 5 sequences:
()()()
()(())
(())()
((()))
(()())
Example:
Input: n = 6
Output: 5
Approach
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long exponentiation(long long a, long long b, long long m){long long res = 1;while (b){if (b % 2)res = res * a % m;a = a * a % m;b /= 2;}return res;}vector<long long> fact, invf;void precompute(int n){fact.assign(n + 1, 1);for (int i = 1; i <= n; i++)fact[i] = fact[i - 1] * i % MOD;invf.assign(n + 1, 1);invf[n] = exponentiation(fact[n], MOD - 2, MOD);for (int i = n - 1; i > 0; i--)invf[i] = invf[i + 1] * (i + 1) % MOD;}long long nCk(int n, int k){//base caseif (k < 0 || k > n)return 0;return fact[n] * invf[k] % MOD * invf[n - k] % MOD;}long long bracketSequencesI(int n){//if n is odd numberif (n & 1)return 0;long long ans = nCk(n, n / 2) - nCk(n, n / 2 + 1);if (ans < 0)ans += MOD;return ans;}int main(){int n = 6;precompute(1e6);cout << bracketSequencesI(n) << "\n";return 0;}
No comments:
Post a Comment