```
public int numTrees(int n) {
if (n==1 || n==0) return n;
int[] dp = new int[n];
dp[0] = 1;
dp[1] = 2;
for (int i = 2; i < n; i++) {
dp[i] += dp[i-1]*2;
for (int j = i-2; j >= Math.ceil((double) i / 2) - 1; j--) {
if (j == i - 2 - j) dp[i] += dp[j]*dp[j];
else dp[i] += dp[j]*dp[i - 2 - j]*2;
}
}
return dp[n-1];
}
```