This year MK is 5 years old. So he decides to learnsome arithmetic. But he was confused by how towrite the brackets. He has already known that the brackets should match whenwriting them correctly. Such as “()(())” is correct but “())(” is not.
Theproblem is that, if there are N pairs of brackets, how many ways that MK can writethem correctly?
Input
There areseveral test cases. Each case contains a number N (1 <= N <= 1000)indicating the pairs of brackets.
Output
For each case,please output the answer mod 1,000,000,007.
Sample Input :
5
7
Sample Output :
42
429
试题分析:
考虑第一个括号一定是左括号,枚举第一个括号匹配的位置。那么递归求解可得f[n] = sigma(f[i] * f[n - i - 1]),其实这道题就是一道典型的卡特兰数的题,具体的卡特兰数在我的博客里有。我直接贴代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000 + 5;
const int MOD = 1000000007;
int n;
lint f[maxn];
int main() {
f[0] = 1;
for(int i = 1; i <= 1000; i++) {
for(int j = 0; j < i; j++) {
f[i] += f[j] * f[i - j - 1] % MOD;
f[i] %= MOD;
}
}
while(scanf("%d", &n) == 1) {
printf("%I64d\n", f[n]);
}
return 0;
}