题目: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,每个数字都可以作为根结点,所以是一层循环,然后当根结点为i时,其生成树情况为小于它的结点的子树乘于大于它的结点的子树的积的和,类似与乘法原理。
例如:当n为4,count[4] = count[0]* count[3] (根结点为1,左子树为空,右子树有2,3,4三个数字继续生成子树,所以为count[3])+ count[1]* count[2] (根结点为2)+count[2]* count[1] (根结点为3)+count[3]*count[0] (根结点为4);
算法复杂度:O(n^2)
代码实现如下:
class Solution {
public:
int numTrees(int n) {
vector<int> count(n+1, 0);
count[0] = count[1] = 1;
for(int i = 2; i <= n; i++) {
for(int j = 1; j <= i; j++)
count[i] +=count[i-j]*count[j-1];
}
return count[n];
}
};