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
Analysis: Just recursively count the number of left sub tree times number of right sub tree.
class Solution { public: int calculate(int n){ int sum = 0; for(int i = 0; i< n ;i++ ) sum += tree[i] * tree[n-1-i] ; // tree[i] : left subTree tree[n-1-i] " right subTree return sum ; } int numTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function tree.resize(n+1,1); for(int i = 2; i <= n ; i++) tree[i] = calculate(i); return tree[n] ; } private : vector<int> tree; };