Problem:
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
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
思路:
二叉搜索树(Binary Search Tree, BST)定义:
所有的左子树值比根节点小,所有的右子树值比根节点大。
http://www.imooc.com/article/270069
题目实际上可以转换为一个包含n个值的已排序数组可以组成多少种不同结构的二叉树问题。
设(F_n)为n个排好序的值可以组成的BST总数。如果将第(i)个值作为根节点,则可以将剩下的值分为两类,比(i)小的值共(i-1)个,放入以第(i)个值为根的左子树,比(i)大的值共(n-i)个,放入以第(i)个值为根的右子树。则只需将左边的值与右边的值分别转换为二叉搜索树即可。故有(F_{i-1} * F_{n-i})种二叉树结构。
n个值总共可以组成的二叉树结构可以分解如下:
以第1个值为根节点:(F_0 * F_{n-1}, F_0=1)
以第2个值为根节点:(F_1 * F_{n-2})
(cdots)
以第(n-1)个值为根节点:(F_{n-2}*F_1)
以第(n)个值为根节点:(F_{n-1}*F_0)
实际上是对称的。
则
[F_n = F_0 * F_{n-1} + F_1 * F_{n-2} + cdots + F_{n-2}*F_1 + F_{n-1}*F_0
]
Solution (C++):
int numTrees(int n) {
if (n == 0 || n == 1) return 1;
int res = 0;
vector<int> dp(n+1, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] += dp[j-1] * dp[i-j];
}
}
return dp[n];
}
性能:
Runtime: 0 ms Memory Usage: 6.2 MB
拓展:
Catalan数
http://www.cppblog.com/MiYu/archive/2010/08/07/122573.html