LeetCode-96. Unique Binary Search Trees

来源:互联网 发布:windows 98 iso 编辑:程序博客网 时间:2024/06/01 08:50

题目:

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,求出能包含1~n个值的二叉搜索树有几棵。

假设 f(i)代表数字i的二叉搜索树有几棵。

默认这些值升序排列并且当作一个个的节点。

n=1,可得到f(1)=1;

n=2, 可选择最左边的值当作根节点,那么最右边节点只能当作右子树,同理,最右节点当作根节点,最左节点当作左子树

即f(2)=f(1)+f(1)=2;

n=3,最左节点当作根节点,则剩下的两个节点就是n=2时的情况,中间节点当作根节点,则可得到 f(左节点的个数)*f(右节点的个数)[根据组合的知识],最右节点当作根节点,左边剩下的两个节点就是n=2时的情况。

f(3)=f(2)+f(1)*f(1)+f(2);

为n时的情况,

f(n)=f(n-1)+f(1)*f(n-2)+…+f(n-2)f(1)+f(n-1);

经本人查找资料,

此类题目与数学上的卡特兰数有密切联系。

以下是代码

public class UniqueBinarySearchTree {    public int numTrees(int n) {        int[] f=new int[n+1];        f[0]=f[1]=1;    for(int i=2;i<=n;i++)        {        for(int j=1;j<=i;j++)        {        f[i]+=f[j-1]*f[i-j];        }        }    return f[n];    }}