96. Unique Binary Search Trees

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,根节点可以是1,2,3,...n。
假设根节点是i,则左子树包括(1,2,3, i -1),右子树包括(i + 1, ..., n)
dp[n] = dp[0]*dp[n-1] + dp[1]*dp[n-2] +...+dp[i - 1] * dp[n-i] + dp[n - 1]*dp[0]

dp[0]*dp[n-1]与dp[n - 1]*dp[0]表示的是不同的,
dp[0]*dp[n-1]表示以1为根节点
dp[n - 1]*dp[0]表示以n作为根节点
class Solution {
public:
    int numTrees(int n) {
        vector<int> dp(n + 1, 0);
        dp[0] = 1;
        dp[1] = 1;

        for(int i = 2; i <= n; i++){
            for(int j = 1; j <= i; j++){
                //以j为根节点
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
};

results matching ""

    No results matching ""