【Leetcode】:Unique Binary Search Trees
2015-03-23 18:28
369 查看
Unique Binary Search Trees
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.
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
public class Solution {
public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
count[1] = 1;
for(int k=2;k<=n;k++)
{
count[k]=0;
for(int i=1;i<=k;i++)
{
count[k]=count[k]+count[i-1]*count[k-i];
}
}
return count
;
}
}
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
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
public class Solution {
public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
count[1] = 1;
for(int k=2;k<=n;k++)
{
count[k]=0;
for(int i=1;i<=k;i++)
{
count[k]=count[k]+count[i-1]*count[k-i];
}
}
return count
;
}
}
相关文章推荐
- LeetCode 95 Unique Binary Search Trees II
- LeetCode Unique Binary Search Trees II
- Leetcode: 95. Unique Binary Search Trees II
- 【题解】【BST】【Leetcode】Unique Binary Search Trees
- leetcode95~Unique Binary Search Trees II
- Unique Binary Search Trees II - Leetcode
- [LeetCode]96 Unique Binary Search Trees
- leetcode — unique-binary-search-trees-ii
- [LeetCode]Unique Binary Search Trees II
- [Leetcode] Unique Binary Search Trees
- LeetCode题解:Unique Binary Search Trees
- LeetCode_96 Unique Binary Search Trees
- leetcode - Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- Leetcode-95.Unique Binary Search Trees II(a representative recursion problem)
- 《leetCode》:Unique Binary Search Trees II
- LeetCode 95. Unique Binary Search Trees II
- [leetcode]95. Unique Binary Search Trees II
- Leetcode 95. Unique Binary Search Trees II 二叉搜索树2 解题报告
- 【leetcode刷题笔记】Unique Binary Search Trees