Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST’s:
public int numTrees(int n) {
// G[n]表示n有几个可能
int [] G = new int[n+1];
G[0] = G[1] = 1;
for(int i=2; i<=n; ++i) {
//j相当于指向根节点的指针
for(int j=1; j<=i; ++j) {
//相当于把G[i]拆分成两部分,左边的可能性+右边的可能性
G[i] += G[j-1] * G[i-j];
}
}
return G[n];
}