LeetCode——Unique Binary Search Trees

Question

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

Solution

动态规划,将大问题划分为小问题,从底向上依次求解。

当规模为1的时候

  • 就只有一种结果

当规模为2的时候

  • 1可以当根,那么总的方案,等于比1小的节点的方案乘上比1大的节点的方案。 dp[2] = dp[1 - 1] * dp[2 - 1]
  • 同理2也可以当跟节点 dp[2] += dp[2 - 1] * dp[2 - 2]

当规模为3的时候

  • dp[3] += (dp[1 - 1] * dp[3 - 1] + dp[2 - 1] * dp[3 - 2] + dp[3 - 1] * dp[3 - 3])

...

Code

class Solution {
public:
    int numTrees(int n) {
        vector<int> dp(n + 1);
        dp[0] = dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = 0;
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/7514700.html