LeetCode:Unique Binary Search Trees(一维DP)

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

题意:给定n,输出n个元素的二叉查找树的个数

思路:
f[i]表示i个元素的BST的个数
BST的特点:以i为根节点的树左子树由[1,..i-1]构成,右子树由[i,...n]构成
则n个元素的 以j为根节点的BST的数目 左子树数目*右子树的数目 f[j-1]*f[n-j+1];
一维动规问题:
f[0]=1;
f[1]=1;
f[2]=f[0]*f[1]+f[1]*f[0];
i个元素
f[i]=∑f(k-1)*f[i-k] (1<=k<=i)
 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         
 8         for(int i=2;i<=n;i++)
 9             for(int k=1;k<=i;k++)
10                 f[i]+=f[k-1]*f[i-k];
11         
12         return f[n];
13         
14     }
15 };

 

posted @ 2015-08-14 10:46  尾巴草  阅读(174)  评论(0)    收藏  举报