给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
class Solution {
public:
int numTrees(int n) {
//f[i]表示以i为根的二叉搜索树个数
//f[i] = G[i-1]*G[n-i]
vector<int> f(n+1,0);
f[0] = 1;
f[1] = 1;
for(int i = 2;i < n+1;++i)
{
for(int j = 1;j < i+1;++j)
{
f[i] +=f[j-1] * f[i-j];
}
}
return f[n];
}
};