题目:
给定n个结点1...n,能够成多少种不同的二分查找树
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
解法:
动态规划。
用f[i]表示i个不同的点能构成多少棵二分查找树。
因为选定一个根后,二分查找树的左子树结点都小于根,右子树结点都大于根。因此,假如我们取定一个点为根节点,那么它的左右子树分别由哪些点组成是固定的。例如n=4。当选择1为根,它的左右子树结点分别是()(2,3,4);选择2为根,左右子树结点分别是(1)(3,4);选择3为根,左右子树结点分别是(1,2)(4);选择4为根,左右子树结点分别是(1,2,3)()。
这样就有递推关系:f[4]=f[0]*f[3]+f[1]*f[2]+f[2]*f[1]+f[3]*f[0]
即:f[i]=f[0]*f[i-1]+f[1]*f[i-2]+...+f[i-1]*f[0]
边界条件:f[0]=f[1]=1
代码:
class Solution {
public:
int numTrees(int n) {
vector<int> f(n+1);
if(n==0) return 0;
f[0]=1;f[1]=1;
for(int i=2;i<=n;i++)
{
f[i]=0;
for(int j=0;j<i;j++)
{
f[i]+=f[j]*f[i-j-1];
}
}
return f[n];
}
};