问题描述
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
分析
给定一个序列1 … n,从序列中构造一个二叉搜索树(BST),我们可以枚举序列中的每个数字i,并且使用该数字作为根,自然,子序列1 …(i-1)在左边将放在根的左边,同样,右边的(i + 1)… n位于根的右边。然后我们可以递归地从子序列构造子树。通过上述方法,我们可以确保我们构建的BST是独一无二的,因为它们具有独特的根源。
问题是计算独特的BST的数量。为此,我们需要定义两个函数:
G(n):长度为n的序列的唯一BST数。
F(i,n),1 <= i <= n:唯一BST的编号,其中编号i是BST的根,序列的取值范围为1〜n。
可以看出,G(n)是我们为了解决问题而需要计算的实际函数。 G(n)可以由F(i,n)导出,最后递归地引用G(n)。
算法(C++)
int numTrees(int n) {
int [] G = new int[n+1];
G[0] = G[1] = 1;
for(int i=2; i<=n; ++i) {
for(int j=1; j<=i; ++j) {
G[i] += G[j-1] * G[i-j];
}
}
return G[n];
}