class Solution {
public:
int numTrees(int n) {
return numTreesHelper(0, n - 1);
}
int numTreesHelper(int start, int end) {
if(start > end) {
return 0;
}
if(start == end) {
return 1;
}
int total = 0;
for(int i = start; i <= end; ++i) {
int left = numTreesHelper(start, i - 1);
int right = numTreesHelper(i + 1, end);
if(left == 0 || right == 0) {
if(left == 0) {
total += right;
continue;
}
if(right == 0) {
total += left;
continue;
}
} else {
total += left * right;
}
}
return total;
}
};
4/12/2014
Leetcode -- Unique Binary Search Trees
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment