96 Unique Binary Search Trees
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
Solution
class Solution {
public:
int numTrees(int n) {
vector<int> result(n+1, 0);
if ( n == 0 or n == 1 ) return 1;
result[0] = 1;
result[1] = 1;
int tmp = 0;
for ( int i = 2; i <= n; i++ ) {
tmp = 0;
for ( int j = 1; j <= i; j++ ) {
tmp += result[j-1] * result[i-j];
}
result[i] = tmp;
}
return result[n];
}
};
Notes
- Catalan number
- Note to use an array to keep record of numTrees(i < n ). Thus one doesn't have to evaluate numTrees(i) and numTrees(n-1-i) for every i.