您的位置:首页 > 产品设计 > UI/UE

【Leetcode】:Unique Binary Search Trees

2015-03-23 18:28 369 查看
Unique Binary Search Trees

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


注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。

分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i  的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
public class Solution {

    public int numTrees(int n) {

        int[] count = new int[n+1];

       count[0] = 1;  

        count[1] = 1;  

        for(int k=2;k<=n;k++)  

        {  

            count[k]=0;  

            for(int i=1;i<=k;i++)  

            {  

                count[k]=count[k]+count[i-1]*count[k-i];  

            }  

        }  

        return count
;  

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法