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

Analyse: We can select 1~N as the root. Suppose the root is i, then we can put j = 0~i - 1 nodes in its left, and put i - j - 1 nodes in its right. 

Runtime: 0ms.

 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         vector<int> dp(n + 1, 0);
 5         dp[0] = 1, dp[1] = 1;
 6         for(int i = 2; i <= n; i++) {
 7             for(int j = 0; j < i; j++) {
 8                 dp[i] += dp[j] * dp[i - j - 1];
 9             }
10         }
11         return dp[n];
12     }
13 };
 
原文地址:https://www.cnblogs.com/amazingzoe/p/5745321.html