Problem:
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Explanation:
给定n,返回可能的包含1-n的搜索二叉树的个数
My Thinking:
My Solution:
Optimum Thinking:
G(n)是n个数字的BST个数,F(n,i)是n个数字且以第i个数字为根的BST个数。F(i,n)=G(i−1)*G(n−i),G(n)=sum(F(i,n))。
Optimum Solution:
class Solution {
public int numTrees(int n) {
int [] G = new int[n+1];
G[0] = G[1] = 1;
for(int i=2; i<=n; ++i) {
for(int j=1; j<=i; ++j) {
G[i] += G[j-1] * G[i-j];
}
}
return G[n];
}
}