[LeetCode]Unique Binary Search Trees

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


找规律。
f(0)=0
f(1)=1
f(2)=f(0)*f(1)+f(1)*f(0)
f(3)=f(0)*f(2)+f(1)*f(1)+f(2)*f(0)
递推公式就是
f(i)=Σf(i-j)*f(j-1)
 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         vector<int> f(n+1,0);
 5         f[0]=1;
 6         f[1]=1;
 7         for(int i=2;i<=n;i++)
 8         {
 9             for(int j=1;j<=i;j++)
10             {
11                 f[i]+=f[i-j]*f[j-1];
12             }
13         }
14         return f[n];
15     }
16 };

 

 
 
posted @ 2015-09-06 17:03  Sean_le  阅读(132)  评论(0编辑  收藏  举报