给出 n,问由 1…n 为节点组成的不同的二叉查找树有多少种?
您在真实的面试中是否遇到过这个题?
样例
给出n = 3,有5种不同形态的二叉查找树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
没有什么好办法,就是找规律
The case for 3 elements example
Count[3] = Count[0]*Count[2] (1 as root)
+ Count[1]*Count[1] (2 as root)
+ Count[2]*Count[0] (3 as root)
Therefore, we can get the equation:
Count[i] = ∑ Count[0...k] * [ k+1....i] 0<=k<i-1
class Solution {
public:
int numTrees(int n) {
int dp[n+1];
fill(dp,dp+n+1,0);
dp[0]=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];
}
};