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
class Solution {
public:
int numTrees(int n) {
int f[n+1];
fill_n(&f[0], n+1, 0);
f[0] = 1;
for (int i = 1; i <=n; i++) {
for (int k = 0; k < i; k++) {
f[i] += f[k]*f[i-k-1];
}
}
return f[n];
}
};
本文介绍了一种计算给定整数n时,可以构造的不同形态的二叉搜索树的数量的方法。例如,当n为3时,共有5种不同的二叉搜索树形态。文章通过一个C++实现的示例代码展示了如何利用动态规划来解决这个问题。
473

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



