原题
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.1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
题目大意
给定一个n个结点的二叉搜索树,求一共有多少个不同类型的二叉搜索树。
解题思路
当n=1时,只有1个根节点,则只能组成1种形态的二叉树,令n个节点可组成的二叉树数量表示为h(n),则h(1)=1; h(0)=0; 当n=2时,1个根节点固定,还有2-1个节点。这一个节点可以分成(1,0),(0,1)两组。即左边放1个,右边放0个;或者左边放0个,右边放1个。即:h(2)=h(0)*h(1)+h(1)*h(0)=2,则能组成2种形态的二叉树。 当n=3时,1个根节点固定,还有2个节点。这2个节点可以分成(2,0),(1,1),(0,2)3组。即h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=5,则能组成5种形态的二叉树。 以此类推,当n>=2时,可组成的二叉树数量为h(n)=h(0)*h(n-1)+h(1)*h(n-2)+...+h(n-1)*h(0)种,即符合Catalan数的定义,可直接利用通项公式得出结果。 令h(1)=1,h(0)=1,catalan数(卡特兰数)满足递归式: h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2) 另类递归式: h(n)=((4*n-2)/(n+1))*h(n-1); 该递推关系的解为: h(n)=C(2n,n)/(n+1) (n=1,2,3,...)
递推公式
f(k)*f(n-1-k):f(k)表示根结点左子树有k个结点,其有的形状是f(k),f(n-1-k)表示右子树有n-1-k个结点 f(n) = 2*f(n-1) + f(1)*f(n-2) + f(2)*f(n-3) + f(3)*f(n-4) + … +f(n-2)*f(1)代码实现
实现类
public class Solution { public int numTrees(int n) { if (n <= 0) { return 0; } else if (n == 1) { return 1; } int[] result = new int[n + 1]; result[0] = 0; result[1] = 1; // 求f(2)...f(n) for (int i = 2; i <= n; i++) { // 求f(i) result[i] = 2 * result[i - 1]; for (int j = 1; j <= i - 1 ; j++) { result[i] += result[j]*result[i - 1 -j]; } } return result[n]; }}