您的位置:首页 > 产品设计 > UI/UE

Unique Binary Search Trees

2016-06-01 15:05 453 查看
题目描述:

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
;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: