// O(n) time, O(1) space
//it is catalan number. Cn = (2n)!/((n+1)!n!)
public int numTrees(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int sum = 1;
for(int i = 2; i <= n; i++) {
sum = 2 * sum * (2 * i - 1) / (i + 1);
}
return sum;
}
// recursive
public int numTrees(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n == 0 || n == 1) return 1;
int sum = 0;
int left = 0;
int right = 0;
for(int i = 0; i < n; i++) {
left = numTrees(i);
right = numTrees(n - i - 1);
sum += left * right;
}
return sum;
}
// DP
public int numTrees(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int[] num = new int[n + 1];
num[0] = 1;
num[1] = 1;
for(int i = 2; i <= n; i++) {
for(int j = 0; j < i; j++) {
num[i] += num[j] * num[i - j - 1];
}
}
return num[n];
}
Unique Binary Search Trees
最新推荐文章于 2022-07-16 08:33:08 发布