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
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
public class Solution {
public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
count[1] = 1;
for(int k=2;k<=n;k++)
{
count[k]=0;
for(int i=1;i<=k;i++)
{
count[k]=count[k]+count[i-1]*count[k-i];
}
}
return count[n];
}
}