Given an integer n, 1 ... n is seeking to nodes of a binary search tree, how many?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, a total of 5 different binary search tree structure:
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];
}
};
When execution: 0 ms, defeated 100.00% of user Unique Binary Search Trees submission of C ++
Memory consumption: 8.3 MB, defeated 11.95% of users in Unique Binary Search Trees submission of C ++