您的位置:首页 > 产品设计 > UI/UE

Leetcode NO.96 Unique Binary Search Trees

2015-02-17 03:50 302 查看
本题题目要求如下:

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=3时,如何用一个普遍的方法得到上面那5种可能性。

看第2,3组,都是root->left是当n=2的两种可能,root->right是当n=0的一种可能,2*1 = 2;看第四组,就是root->left是n=1的一种可能,root->right是n=1的一种可能,1*1 = 1;看第1,5组,root->left是n=0的一种可能,root->right是n=2的两种可能,1*2 = 2

由此可以得到一个普遍的公式:dp(3) = dp(0)*dp(2) + dp(1)*dp(1)+dp(2)*dp(0)。

再将公式推广到dp(n),即可得到本题的解。

class Solution {
public:
    int numTrees(int n) {
        int res = 0;
        vector<int> dp(n+1, 0);
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; ++i) {
            for (int j = 0; j < i; ++j)
                dp[i] += dp[j] * dp[i-1-j];
        }
        return dp
;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: