首页 > 其他 > 详细

leetcode------Unique Binary Search Trees

时间:2015-02-20 14:04:29      阅读:281      评论:0      收藏:0      [点我收藏+]
标题: Unique Binary Search Trees
通过率: 37.0%
难度: 中等

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

本题对我的难度是,我忘记了什么是BST,然后查了下才知道BST就是排序树,如果用中序遍历一遍结果就是12345678这样的有序数列。

那么如何构建,本题有个特点就是考察卡塔兰数,如果对卡塔兰数推导公式了解的话本题就很容易做出来了。

技术分享

它也满足

技术分享

 

求Cn+1  的前提就是知道了Cn,

举例如下:

1、n=0时,res[0]=1;

2、n=1时,res[1]=1;

3、n=2时,res[2]=res[0]*res[1]+res[1]*res[0]

也就说根元素左边和根元素右边可能的情况都要列出来。

具体看代码:

 1 public class Solution {
 2     public int numTrees(int n) {
 3         int []result=new int[n+1];
 4         result[0]=1;
 5         result[1]=1;
 6         for(int i=2;i<n+1;i++){
 7             result[i]=0;
 8             for(int j=0;j<i;j++){
 9                 result[i]+=result[j]*result[i-1-j];
10             }
11         }
12         return result[n];
13     }
14 }

 

leetcode------Unique Binary Search Trees

原文:http://www.cnblogs.com/pkuYang/p/4296498.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!