I don't think that your code works. Do you mean the number of unique Binary Search Trees with numbers from 1
to n
?
For n = 3
, the number should be 5
. But your code gave me the result 2
.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Here is my solution:
int numTrees(int n) {
int dp[n+1];
memset(dp, 0, sizeof(dp));
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];
}
For Catalan Number, P(3) = P(1)P(2) + P(2)P(1)
.
But in this problem, P(3) = P(0)P(2) + P(1)P(1) + P(2)P(0)
.
So, I guess it's not Catalan Numbers. Hope this could help you.