题目描述:
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我是先做的 Unique Binary Search Trees II ,然后用那个方法递归,超时了,应该用动态规划的方法。
递归方法代码如下:(超时!)
public int numTrees(int n) {
return getNum(1, n);
}
public int getNum(int left,int right){
int result=0;
if(left>=right)
return 1;
for(int i=left;i<=right;i++){
int leftnum=getNum(left, i-1);
int rightnum=getNum(i+1, right);
result+=leftnum*rightnum;
}
return result;
}
AD代码如下:
public static int numTrees(int n) {
int[] cnt = new int[n+1];
cnt[0] = 1;
cnt[1] = 1;
for(int i=2; i<=n; i++){
for(int j=0; j<=i-1; j++){
cnt[i] += cnt[j] * cnt[i-1-j];
}
}
return cnt[n];
}