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
 1 public class Solution {
 2     public int numTrees(int n) {
 3         int count [] = new int [n+1];
 4         count[0] = 1;
 5         count[1] = 1;
 6         for(int i=2;i<=n;i++){
 7             for(int k=0;k<=i-1;k++){
 8                 count[i] += count[i-k-1]*count[k];
 9             }
10         }
11         return count[n];
12     }
13 }
View Code

 

posted @ 2014-02-19 00:27  krunning  阅读(174)  评论(0编辑  收藏  举报