题目链接:链接
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
解题思路:设输入数值为n, f(n)为n个数形成的唯一BST的棵树,则有:
1. 1-n每个数值可作为根节点形成唯一的BST;
2. 设ln、rn分别为以root为根节点,左右节点的个数, 所形成的唯一的BST有 f(ln) * f(rn) 棵, 其中ln + rn + 1 = n;
可得递推式:f(n) = f(0) * f(n-1) + … + f(n-1) * f(0), 其中,f(0) = f(1) = 1; 可划分为独立的子问题计算,动态规划思路可解,代码如下:
int numTrees(int n) {
vector<int> a(n+1, 0);
a[0] = a[1] = 1;
for(int i = 2; i <= n; i++) {
for(int j = 0; j < i; j++){
a[i] += a[j] * a[i-j-1];
}
}
return a[n];
}
网上学习得知,该数列为卡特兰数,其O(n) 的递推公式为:
f(n)=(2n)!/(n!*(n+1)!) (n=1,2,3,…),计算时应考虑是否整除的问题即可。