[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.
这道题为什么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;
}
};
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# 96、Unique Binary Search Trees
- Unique Binary Search Trees II [leetcode]
- 【Leetcode】【python】Unique Binary Search Trees
- 【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
- LeetCode Unique Binary Search Trees II
- leetcode -- Unique Binary Search Trees
- [LeetCode] 121: Unique Binary Search Trees
- Leetcode:unique_binary_search_trees
- LeetCode: Unique Binary Search Trees II
- Unique Binary Search Trees leetcode java
- 【leetcode】 Unique Binary Search Trees II (middle)☆
- LeetCode——Unique Binary Search Trees II
- Leetcode-Unique Binary Search Trees
- Leetcode 96 Unique Binary Search Trees(独一的二叉搜索树)
- [leetcode] 95. Unique Binary Search Trees II 解题报告
- 【LeetCode】96 - Unique Binary Search Trees
- LeetCode Unique Binary Search Trees
- LeetCode | Unique Binary Search Trees(二叉搜索树的个数)
- [LeetCode] Unique Binary Search Trees
- leetcode Unique Binary Search Trees II