Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
DP方法,dp[i]表示有i个数可以形成不同的BST个数,分别遍历顶点元素为1--n,即可
public class Solution {
public int numTrees(int n) {
int[]rst = new int[n+1];
rst[0] = 1;
for(int i=1; i<n+1; i++){
for(int j=1; j<=i; j++){
rst[i] += rst[j-1] * rst[i-j];
}
}
return rst[n];
}
}