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最重要的是这个返回条件:
if(start >= end)
return 1;
AC代码如下:
public class Solution {
public int count(int start, int end){
if(start >= end)
return 1;
else{
int sum = 0;
for(int i = start; i <= end; i++){
int left = count(start, i - 1);
int right = count(i + 1, end) ;
sum = left * right + sum;
}
return sum;
}
}
public int numTrees(int n) {
return count(1, n);
}
}