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

Unique Binary Search Trees (leetcode)

2014-11-03 16:39 363 查看
题目:

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

题解:递归,为了避免递归的时间浪费,用空间换取时间方法来做,即把每次结果都用数组保存,计算下一个数据时,只需要查数组即可快速得到哦结果。
#include<iostream>
using namespace std;

int numTrees(int n)
{
int *tempResult=new int[n+1];
tempResult[0]=1;
tempResult[1]=1;
for(int i=2;i<=n;i++)
{
tempResult[i]=0;
for(int j=0;j<(i>>1);j++)
{
tempResult[i]+=tempResult[j]*tempResult[i-1-j];
}
tempResult[i]*=2;
if(i&1==1)//如果i是奇数
tempResult[i]+=tempResult[i>>1]*tempResult[i>>1];
}
/*上面的属于屏蔽掉的这部分的优化,即只需要计算一半,另一半对称。
//如计算n=5,tempResult[0]*tempResult[4]和tempResult[4]*tempResult[0]是等价的,
//只需要最后重新计算tempResult[2]*tempResult[2]即可
for(int i=2;i<=n;i++)
{
tempResult[i]=0;
for(int j=0;j<i;j++)
{
tempResult[i]+=tempResult[j]*tempResult[i-1-j];
}
}*/
int result=tempResult
;
delete []tempResult;
return result;
}

int main()
{
cout<<numTrees(5)<<endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: