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

[LeetCode] Unique Binary Search Trees

2014-08-02 21:17 507 查看
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


这道题为什么AC率那么高。。。主要是我开始没接触过线性规划。。。

当n==0时,显然是0

当n==1时,根节点只有1中选择,结果是1

当n==2时,根节点有2种选择,结果是2

当n==3时,根节点有3种选择, 确立完根节点以后存在左右树的分配,即可以用上面的结果进行建树,左右方法数相乘即得结果

类推

class Solution {
public:
int numTrees(int n) {
if (n <= 1)
return n;
int *way = new int[n + 1];
way[0] = 1;
way[1] = 1;
for (int i=2; i<=n; i++)
{
way[i] = 0;
for (int j=0; j<i; j++)
{
int left = way[j];
int right = way[i - j - 1];
way[i] += left * right;
}
}
int ret = way
;
delete [] way;
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++