Unique Binary Search Trees
Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?
For example,
Givenn= 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
动态规划法
本题关键:如何填表,如何得到计算公式.
需要很仔细画图,一步一步找出规律。
Catlan公式是可以计算这样的题目的,不过Catalan公式也不好理解,还是写个循环解决吧。
class Solution { public: int numTrees(int n) { vector<int> ta(n+1); ta[0] = 1; ta[1] = 1; ta[2] = 2; for (int i = 3; i <= n; i++) { int mid = (i-1)/2; for (int j = 0; j < mid; j++) { ta[i] += ta[j] * ta[i-j-1] *2; } if (i%2) ta[i] += ta[mid] * ta[mid]; else ta[i] += ta[mid+1] * ta[mid] * 2; } return ta[n]; } };
//2014-2-15 update
int numTrees(int n)
{
if (n < 3) return n;
int *A = new int[n+1];
A[0] = 1, A[1] = 1, A[2] = 2;
for (int i = 3; i <= n; i++)
{
int half = i/2;
A[i] = 0;//注意要初始化
for (int j = 1; j <= half; j++)
A[i] += A[j-1] * A[i-j] *2;//注意细节是+=
if (i%2 == 1) A[i] += A[half]*A[half];
}
return A[n];
}
//2014-2-15 update 2
int numTrees2(int n)
{
int *A = new int[n+1];
A[0] = 1;
for (int i = 1; i <= n; i++)
{
A[i] = 0;//注意要初始化
for (int j = 1; j <= i; j++)
A[i] += A[j-1] * A[i-j];//注意细节是+=
}
return A[n];
}
下面是参考资料:
http://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0
http://en.wikipedia.org/wiki/Catalan_number