【发布时间】:2017-02-01 20:45:03
【问题描述】:
给定 n,有多少个结构唯一的 BST(二叉搜索树)存储值 1...n?
例如, 给定 n = 3,总共有 5 个唯一的 BST。
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
我有这个解决方案:
/**
* Solution:
* DP
* a BST can be destruct to root, left subtree and right subtree.
* if the root is fixed, every combination of unique left/right subtrees forms
* a unique BST.
* Let a[n] = number of unique BST's given values 1..n, then
* a[n] = a[0] * a[n-1] // put 1 at root, 2...n right
* + a[1] * a[n-2] // put 2 at root, 1 left, 3...n right
* + ...
* + a[n-1] * a[0] // put n at root, 1...n-1 left
*/
int numTrees(int n) {
if (n < 0) return 0;
vector<int> trees(n+1, 0);
trees[0] = 1;
for(int i = 1; i <= n; i++)
for (int j = 0; j < i; j++)
trees[i] += trees[j] * trees[i-j-1];
return trees[n];
}
因为这个答案是很久以前给出的,无法触及这个 'dragonmigo' 家伙。 这个解决方案被接受了,我的问题是:
在注释中,trees[0] 指的是 case 1。 (0+1 = 1)
如果是这样,trees[n-1] 应该引用 case 1...n 而不是 case 2...n。 (n-1+1=n)
我的想法错了吗?
附言我知道这实际上是一个加泰罗尼亚数,我知道使用推导公式解决它的算法。
【问题讨论】:
-
你能解释清楚你想问什么吗?它是加泰罗尼亚数字。你想要它的证据还是别的什么?
-
这不是我的意思。我的观点是注释中trees[n]的定义与代码中trees[n]的实际含义相冲突。
-
就像这样 让 a[n] = 给定值的唯一 BST 的数量 1..n 那么 a[0] 应该代表什么?
标签: algorithm binary-search-tree catalan