题目
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个不同的数可以组成的二叉树数量是相同的。
递推公式:
第1~m时的合法数数量n(m)=n(0)*n(m-1)+n(1)*n(m-2)+...n(m-1)*n(0)。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int numTrees(int n) {
if(n==0)
return 0;
vector<int> solution; //表示1到n的各个数的二叉树数量
solution.push_back(1);
for(int i=1;i<=n;i++) //递推
{
solution.push_back(0);
for(int j=0;j<i;j++)
solution[i]+=solution[j]*solution[i-j-1];
}
return solution[n];
}
};