leetcode------Unique Binary Search Trees

标题: 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这样的有序数列。

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

C_0 = 1 quad mbox{and} quad C_{n+1}=sum_{i=0}^{n}C_i\,C_{n-i}quadmbox{for }nge 0.

它也满足

C_0 = 1 quad mbox{and} quad C_{n+1}=frac{2(2n+1)}{n+2}C_n,

求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 }
原文地址:https://www.cnblogs.com/pkuYang/p/4296498.html