Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
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
int numTrees(int n) {
vector<int> SumNumtrees(n + 1, 1);
for (int i = 2; i <= n; ++i){
SumNumtrees[i] = 0;
for (int k = 0; k < i; ++k)
{
SumNumtrees[i] += SumNumtrees[k] * SumNumtrees[i - k - 1];
}
}
return SumNumtrees[n];
}
本文介绍了如何使用递归算法计算给定整数n时,能够构造出的不同结构的唯一二叉搜索树的数量。通过构建动态规划表,逐个填充每个子问题的解,最终得到n个元素时的唯一二叉搜索树总数。
475

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



