96. Unique Binary Search Trees
Description
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.
Analysis
这道题的意思其实就是求,给定一个数n,得出它的二叉搜索树有多少种。
一开始我是没有头绪的。
后来我就在想当我们求当前数i有多少种二叉搜索树时,其实就是在求它左子树和它的右子树的乘积。
分析一下
当n = 0时,数目是1
当n = 1时,数目是1
当n = 2时,数目是2 即n2=n0*n1+n1*n0
当n = 3时,数目是5 即n3=n2*n0+n1*n1+n0*n2
以此类推,我们不难得到递推式
以下是我的代码
Code
class Solution {
public:
int numTrees(int n) {
if(n == 0) return 0;
int res[n+1];
res[0] = 1;
res[1]= 1;
//res[2] = 2;
for(int i = 2 ; i <= n;++i){
res[i] = 0;
}
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];
}
};