leetcode96 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

思路:
[a,b]的二叉搜索树可分为三类:
[a+1,b]的二叉搜索树插入a的右子树;
[a,b-1]的二叉搜索树插入b的左子树;
以[a+1,b-1]区间内的任一节点i作为根节点,[a,i-1]形成的二叉搜索树插入i的左子树,[i+1,b]形成的二叉搜索树插入i的右子树。
 1 class Solution {//递归超时,动态规划可以
 2 public:
 3     int numTrees(int n) {
 4         if(n<1)
 5             return 0;
 6         
 7         vector<int> j(n+1,0);
 8         j[1]=1;
 9         for(int i=2;i<=n;i++)
10         {
11             int temp=2*j[i-1];
12             for(int k=2;k<=i-1;k++)
13                 temp+=j[k-1]*j[i-k];
14             j[i]=temp;
15         }
16         return j[n];
17     }
18 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5105662.html