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
Show Company Tags
Show Tags
Show Similar Problems
 
 
这道题用DP做,首先举几个例子。
当n为3的时候,
root为1时,左侧为0,右侧为2个元素
root为2时,左侧右侧各一个元素
root为3时,左侧为2,右侧为0.
所以n为3的时候,总共情况为dp(0)*dp(2)+dp(1)*dp(1)+dp(2)*dp(0);
推到generic的情况,对于dp[n],
就是dp[0]*dp[n-1]+dp[1]*dp[n-2]+dp[2]*dp[n-3]+...+dp[n-1]*dp[0].
 
代码为
public int NumTrees(int n) {
        var dp = new int[n+1];
        dp[0]=1;
        dp[1]=1;
        
        for(int i=2;i< n+1;i++)
        {
            for(int j = 0;j<i;j++)
            {
                dp[i] += dp[j]*dp[i-j-1];
            }
        }
        return dp[n];
    }
原文地址:https://www.cnblogs.com/renyualbert/p/5972376.html