163. Different Binary Search Trees
Given n, ask how many different binary search trees composed of 1...n nodes?
Sample
Example 1:
Input: n = 3
Output: 5
Explanation: There are 5 different forms of binary search trees:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
int fn(int n)
{
if(n == 0 || n ==1)
{
return 1;
}
if(n==2)
{
return 2;
}
int sum = 0;
if(n % 2 == 0)
{
for(int i=0; i<n/2;i++)
{
sum += fn(i) * fn(n-1-i);
}
sum *=2;
}
else
{
for(int i=0; i<n/2;i++)
{
sum += fn(i) * fn(n-1-i);
}
sum *=2;
sum += fn(n/2) * fn(n/2);
}
return sum;
}