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.
class Solution {
public:
int helper(int start, int end){
// not a add up relationship,
// instead it is multiplication relationship.
if (start>=end){
return 1;
}
//else if (start==end)
// return 1;
else{
int total = 0;
for (int i=start;i<=end;i++){
total += helper(start,i-1) *
helper(i+1,end);
}
return total;
}
}
int numTrees(int n) {
return helper(1,n);
}
};