这题真是想不大明白,上网查了查。发现自己对BST的认识还是不够啊。
这里有个讲解(印度人口音真难懂)。
重点是这个公式:
核心思想是:当k是BST的根节点时,[1,k-1]构成左子树,[k+1,n]构成右子树。根节点确定以后,左子树和右子树的排列是任意的。这样就得到了上面的递归公式。这是一个一维的动态规划,代码很简单。
public class Solution {
public int numTrees(int n) {
int[] result = new int[n + 1];
Arrays.fill(result, 0);
//when there is no node or only one node, the number of trees is obviously one
result[0] = 1;
result[1] = 1;
for(int i = 2; i <= n; i++){
for(int j = 1; j <= i; j++){
result[i] += result[j - 1] * result[i - j];
}
}
return result[n];
}
}
另外这正是Catalan Number.