Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example
Given n = 3, there are a total of 5 unique BST’s.

描述
给出一个 n,能组成多少种不同的二叉搜索树
分析
假设有 n 个节点,任选其中的一个节点为根,所可行的二叉搜索树的数量等于左右子树二叉搜索树数量的乘积
例如:
n = 0 , h(0) = 1n = 1 , h(1) = 1n = 2 , h(2) = h(0)h(1) + h(1)h(0), 即取一个节点为根节点后,左子树为空,右子树一个节点,或者左子树一个节点,右子树为空
观察可得,这是卡特兰数的特征,由此可以推出以下解法:
代码
$h(0)=1 \; , \; h(1)=1$
$h(n)=h(0)h(n-1)+h(1)h(n-2)+ \cdots +h(n-1)h(0)$
1 | public class Solution { |
$h(1)=1$
$h(n)=h(n-1)(4n-2)/(n+1)$
1 | public class Solution { |