1、定义:是一种经典的组合数,经常出现在各种计算中,
其前几项为 : 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020,
2、公式:
(1)、一般公式 ( 当 n > 35 时, long long )
令 h(0)=1, h(1)=1,catalan数满足递推式:
(2)
(3)
(4)
还可以解决如下问题:
1.进出栈序列:n 个元素进栈序列为:1,2,3,4,...,n,则有多少种出栈序列。
我们将进栈表示为 +1,出栈表示为 -1,则 1 3 2 的出栈序列可以表示为:+1 -1 +1 +1 -1 -1。所有可能的序列情况-非法序列即可,C(n,2*n)-C(n-1,2*n)。
入栈的数的个数总是要大于或者等于出栈数的个数
2.括号匹配:括号生成
3.有n+1个叶子的满二叉树的个数?
4.电影购票:
还有一些问题可以解决,但是自己对卡特兰数的理解运用还不够,之后会回来填坑。
卡特兰数实现代码:
import java.math.BigInteger;
// 打印前 n 个卡特兰数
int n = 20;
BigInteger ans = BigInteger.valueOf(1);
System.out.println("1:" + ans.toString());
BigInteger four = BigInteger.valueOf(4);
BigInteger one = BigInteger.valueOf(1);
BigInteger two = BigInteger.valueOf(2);
for (int i = 2; i <= n; i++) {
BigInteger bi = BigInteger.valueOf(i);
ans = ans.multiply(four.multiply(bi).subtract(two)).divide(bi.add(one));
System.out.println(i + ":" + ans.toString());
}
组合数的代码:
public BigInteger pailie(int m, int n) {
int fenzi=1;
int fenmu=1;
for(int i=n+1; i<=m; i++)fenzi*=i;
for(int j=1; j<=(m-n); j++)fenmu*=j;
return BigInteger.valueOf(fenzi/fenmu);
}