Leetcode96.Unique_Binary_Search_Trees

对于有n个节点的二叉树,由于根节点是固定的,所以n个节点的组合是(n-1)个节点组成的两个子树所有可能性乘积的和即, h ( n ) = ∑ i = 0 n − 1 h ( i ) ∗ h ( n − 1 − i ) h(n)=\sum_{i=0}^{n-1}{h(i)*h(n-1-i)} h(n)=i=0n1h(i)h(n1i)
这个递推公式即为卡塔兰数的定义式,其通项公式为:
h ( n ) = 1 n + 1 C 2 n n h(n)=\frac{1}{n+1}C_{2n}^{n} h(n)=n+11C2nn
由此,我们即可算出答案(卡塔兰数具体分析见卡塔兰(Catalan Number)数和斯特林公式(Stirling Approximation)分析
时间复杂度: O ( 4 n n 3 2 ) O(\frac{4^n}{n^{\frac{3}{2}}}) O(n234n)(此界随n增大而渐进)
C++代码:

class Solution {
public:
	int numTrees(int n) {
		if (n == 1)
			return 1;
		long long result = 1,record = n;
		for (int i = 2 * n; i > n; i--)
		{
			result *= i;
			while (record > 1 && result / record * record == result)
				result /= record--;
		}
		while (record > 1)
			result /= record--;
		return result / (n + 1);
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值