96. Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

给出整数n,有多少中不同的存储着1到n的二叉搜索树。

For example,
Given n = 3, there are a total of 5 unique BST's.

这个题需要通过动态规划的方式来解。

首先找规律,an为存储着不同的1到n的二叉搜索树的数量,发现:

a1=1;

a2=2*a1=2;

a3=2*a2+a1*a1=5;

a4=2*a3+2*a2=14;

a5=2*a4+2*a3*a1+a2*a2=42;

……;

a2n=2*a2n-1+2*a2n-2*a1+…+2*an*an-1;

a2n+1=2*a2n+2*a2n-1*a1+…+an*an;

为了统一,设a0=1,得出:

a2n=2*a2n-1*a0+2*a2n-2*a1+…+2*an*an-1;

a2n+1=2*a2n*a0+2*a2n-1*a1+…+2*an*an-an*an;

AC代码如下:

 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         vector<int> r={1,1};
 5         for(int i=2;i<=n;i++){
 6             int now=0;
 7             for(int j=i/2;j<i;j++){
 8                 now+=2*r[j]*r[i-j-1];
 9             }
10             if(i%2)now-=r[i/2]*r[i/2];
11             r.push_back(now);
12         }
13         return r[r.size()-1];
14     }
15 };

 

posted @ 2016-07-18 17:42  ShawnChang  阅读(101)  评论(0编辑  收藏  举报