这题简单点记就是利用卡特兰数,当n=0时,只有空树;当n=1时,只有一棵树;当n=2时,有1为根和2为根两种情况,有两棵树。此后每种情况下,BST的个数满足a[n] = Σa[i]a[n-i-1] (i = 0, 1, …, n-1)。
代码实现如下,复杂度O(n²):
class Solution {
public:
int numTrees(int n) {
int* a = new int[n + 1];
a[0] = 1;
a[1] = 1;
for (int i = 2; i <= n; i++) {
a[i] = 0;
for (int j = 0; j < i; j++) {
a[i] += a[j] * a[i - j - 1];
}
}
int temp = a[n];
delete []a;
return temp;
}
};