问题描述:
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
思路:暂时只想到了O(n^2)的算法,也AC了。总感觉这道题应该有某种推导公式实现O(n)的算法....先做个记录,到时再改
O(n^2)算法: 设a[i]为i个数所产生的BST个数(i从2遍历到n)。设j为以数j为树根的BST个数,j从1遍历到i做a[j-1]与a[i-j]的乘积,然后累加到a[i]中。乘积相当于左边有j-1个节点组成的BST,右边有i-j个节点组成的BST,二者组成的以j为树根的BST个数。
代码:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
class Solution {
public:
int numTrees(int n) {
int a[4000];
memset(a,0,sizeof(a));
a[1]=1;
a[0]=1;
for(int i=2;i<=n;i++)
for(int j=1;j<=i;j++){
a[i]+=(a[j-1]*a[i-j]);
}
return a[n];
}
};
int main()
{
cout<<(new Solution())->numTrees(1);
}