1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 /**
* key point 1: all left nodes are less than root and all right nodes are greater root.
* key point 2: number of current node is the product of number of all left and number of all right.
*/
class Solution {
public int numTrees(int n) {
if (n <= 1) return 1;
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++) {
dp[i] += dp[j]*dp[i  j  1];
}
}
return dp[n];
}
}
