给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int numTrees(int n) {
vector<int>status;
status.push_back(1);
for(int i=1;i<=n;i++)
{
status.push_back(0);
for(int j=0;j<i;j++)
{
status[i]+=status[j]*status[i-1-j];
}
}
return status[n];
}
};
执行用时 : 0 ms, 在Unique Binary Search Trees的C++提交中击败了100.00% 的用户
内存消耗 : 8.3 MB, 在Unique Binary Search Trees的C++提交中击败了11.95% 的用户