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
/ / \ \
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的数。求这n个数能组成的二叉搜索树的个数。二叉搜索树的定义为一个节点其左子树的大小小于其自身。右子树的大小均大于其本身的值。因此对于节点i,其左子树的数字只能是[1~i-1],右子树的节点的数值为[i+1~n],如果其左子树的可能个数为m,右子树可能个数为n,对于以节点i为根的合符条件的树的个数为m*n。对于1到n的数字。其每个都可以为树的根。代码如下
class Solution {
public:
int numTrees(int n) {
vector<int>res(n+1,0);
res[0]=1;
res[1]=1;
for(int i=2;i<=n;i++)
for(int j=0;j<i;j++)
res[i]+=res[j]*res[i-j-1];
return res[n];
}
};