leetcode--Unique Binary Search Trees

1.题目描述

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

2.解法分析

对于给定的n,其不同的BST可按根节点分类,即根节点分别为1…n,然后递归计算,由于递归耗时,可以用一张表存放中间结果。于是就有了下面的解法:

class Solution {
public:
    int numTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!n||n==1)return 1;
        
        
        vector<int> dp;
        dp.assign(n+1,0);
        dp[0]=1;
        dp[1]=1;
        
        for(int i=2;i<=n;++i)
        {
            for(int j=0;j<=i-1;++j)
            {
                dp[i]+=dp[j]*dp[i-1-j];
            }
        }
        
        return dp[n];
    }
};
posted @ 2013-08-17 23:46  曾见绝美的阳光  阅读(220)  评论(0编辑  收藏  举报