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的自然数,表示这个二叉搜索树的结点数量,然后求这个二叉搜索树有多少种。其实一拿到这个题,首先想到的,题目肯定是符合一定的数学规律,当n=0时,数量为1,n=1时,数量为1,n=2时,数量为2,n=3时数量为6。而且深层地去看,假设以3为根,那么左子树有2个可排序的结点,右子树有0个可排序的结点。然后还有分别以1和2为根的情况。那么这里就为:f(3)=f(2)*f(0)+f(1)*f(1)+f(0)*f(2)。这样推导下去得到了一个递推式:
f(i) = ∑ f(k-1) * f(i - k); (k=1到n)
所以很明显是一个动态规划的问题。所以代码如下。
Code:(LeetCode运行0ms)
class Solution {
public:
int numTrees(int n) {
//一维动态规划
vector<int> result(n + 1, 0);
result[0] = 1;
result[1] = 1;
for (int i = 2; i <= n; i++) {
for (int k = 1; k <= i; k++) {
result[i] += result[k - 1] * result[i - k];
}
}
return result[n];
}
};