[leetcode] 96. Unique Binary Search Trees

来源:互联网 发布:kali linux安装输入法 编辑:程序博客网 时间:2024/05/29 18:10

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


解法一:

catalan number,然后用dp去做。分析一下:dp[0] = 1, dp[1] = 1, dp[n]的个数是左右subtree种数的乘积

dp[2]= dp[0]*dp[1] (root为1)

+ dp[1]*dp[0] (root为2)

dp[3] = dp[0]*dp[2](root为1)

+ dp[1]*dp[1] (root为2)

+ dp[2]*dp[0] (root为3)

所以公式就是 dp[n] = sum_(0:n-1) dp[i]*dp[n-i-1]

class Solution {public:    int numTrees(int n) {        vector<int> dp(n+1);        dp[0] = 1;        for(int i=1; i<=n; i++){            for(int j=0; j<i; j++)                dp[i] += dp[j]*dp[i-j-1];        }        return dp.back();            }};





0 0