码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Unique Binary Search Trees

时间:2015-09-06 18:11:04      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

 
 

[LeetCode]Unique Binary Search Trees

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4786616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!