参见百度百科:https://baike.baidu.com/item/%E5%8D%A1%E7%89%B9%E5%85%B0%E6%95%B0
卡特兰数的前15项为:1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845
递推关系为:h(n)=h(n-1)*(4*n-2)/(n+1);
或者:h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,…)
实现代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=105;
const LL mod=1e9+9;
LL power(LL a,LL n)
{
LL ret=1,res=a;
while(n){
if(n&1) ret=ret*res%mod;
res=res*res%mod;
n>>=1;
}
return ret;
}
LL inv(LL a)
{
return power(a,mod-2);
}
LL catalan[maxn];
int main() {
ios::sync_with_stdio(false);
catalan[0]=1,catalan[1]=1;
int n=100;
for(int i=2;i<=n;i++){
catalan[i]=(catalan[i-1]*(4*i-2))%mod*inv(i+1)%mod;
}
for(int i=1;i<=n;i++) cout<<catalan[i]<<',';
return 0;
}
应用:
1,一个无限长的栈,进栈顺序为1,2,3,,,,n,则总共的则又catalan[n]种出栈序列