题目:
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
思路:
n=0,1,2时,可以直接给出答案。
当n>=3时,要考虑几种情况:3 插入 1,2 中,插入头部,插入尾部,插入中间。头和尾均有 numTrees(3-1)种结果,插入中间就要考虑 左右两侧数字的可能性。
扩展的n的情况,依旧头尾均有numTrees(n-1)种结果,插入中间i的位置,要考虑 1~i,i+1~n-1 左右两侧的可能,其结果为 numTrees(i)*numTrees(n-1-i)
用递归简单,而且明白。
代码:
public class Solution {
public int numTrees(int n) {
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 2;
int sum=0;
int i=n-2;
while(i>0){
sum=numTrees(n-1-i)*numTrees(i)+sum;
i--;
}
sum=sum+2*numTrees(n-1);
return sum;
}
}