题目:
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Constraints:
1 <= n <= 19
卡特兰数:递归公式
f(n) = f(0)* f(n-1) + f(1)* f(n-2) + f(2)*f(n-3)+......+f(n-1)*f(0)
代码如下:
class Solution {
public:
int numTrees(int n){
vector<int> res(n + 1);
res[0] = 1, res[1] = 1;
for(int i = 2; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
res[i] += res[j-1]*res[i-j];
}
}
return res[n];
}
};

本文探讨了如何使用卡特兰数计算不同结构的二叉搜索树数量,通过递归公式和具体代码实现,展示了当输入为3时,共有5种独特的二叉搜索树结构。
335

被折叠的 条评论
为什么被折叠?



