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

[LeetCode][Java] Unique Binary Search Trees

2015-05-20 21:09 447 查看

题目:

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,计算二叉排序树的结构种类。

算法分析:

* 本题使用一维线性规划解决。

* 如果n等于0时,结果为0;

* 如果n等于1时,只有一个节点,结果为1;

* 如果n等于2时,根节点有两种选择,结果为2;

* 如果n大于3时,根节点有n种选择,确定根节点后分别计算左右子树的可能情况,

* 然后相乘就是当前根节点下所有的变形种类,

* 之后在求和即可。算法实现如下:

代码如下:

public class Solution
{
public  int numTrees(int n)
{
int rec[]=new int[n+1];
int i,k;
int tem=0;
if (n == 1)
return 1;
if (n == 2)
return 2;
rec[0]=1;
rec[1]=1;
rec[2]=2;

for(i=3;i<=n;i++)
{
tem=0;
for(k=0;k<i;k++)
{
tem+=(rec[k]*rec[i-k-1]);
}
rec[i]=tem;
}
return rec
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: