problem
wrong approach
class Solution {
public:
int numTrees(int n) {
vector<int> dp(23, 0);
dp[0] = 1, dp[1] = 1, dp[2] = 2;
for(int i=3; i<=n; i++){
if(i%2){
for(int t=(i-1)/2+1; t<=i-1; t++)
dp[i] += dp[t]*dp[i-1-t];
dp[i] += dp[(i-1)/2]*dp[(i-1)/2];
}else{
for(int t=i/2; t<=i-1; t++)
dp[i] += dp[t]*dp[i-1-t];
dp[i] *= 2;
}
}
return dp[n];
}
};
approach 1
class Solution {
public:
int numTrees(int n) {
vector<int> dp(20, 0);
dp[0]=1, dp[1]=1;
for(int i=2; i<=n; i++)
for(int j=1; j<=i; j++)
dp[i] += dp[j-1]*dp[i-j];
return dp[n];
}
};