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

[leetcode] Unique Binary Search Trees

2013-08-18 21:20 302 查看
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


class Solution {
public:
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0)
return 1;
else{
int num=0;
for(int i=0 ; i<n ; i++)
num+=numTrees(i)*numTrees(n-i-1);
return num;
}

}
};

如果想做一个非递归的,就用动态规划去做,代码如下:

class Solution {
public:
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int (*p)[2]=new int[n+1][2];
memset(p,0,sizeof(int)*(n+1)*2);
int num;
p[0][0]=1;
p[0][1]=1;
for(int i=1 ; i<=n ; i++){
num=0;
for(int j=0 ; j<i ; j++)
num+=p[j][0]*p[i-j-1][1];
p[i][0]=num;
p[i][1]=num;
}
return p
[0];
}
};


效率比递归的要高很多很多!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: