给出 n,问由 1...n 为节点组成的不同的二叉查找树有多少种?
例如,
给出 n = 3,则有 5 种不同形态的二叉查找树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
详见:https://leetcode.com/problems/unique-binary-search-trees/description/
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1,0);
dp[0]=1;
dp[1]=1;
for(int i=2;i<=n;++i)
{
for(int j=0;j<i;++j)
{
dp[i]+=dp[j]*dp[i-j-1];
}
}
return dp[n];
}
};
参考:https://www.cnblogs.com/grandyang/p/4299608.html