leetcode 难题 Unique Binary Search Trees
来源:互联网 发布:安全的网络兼职 编辑:程序博客网 时间:2024/05/16 07:00
Unique Binary Search Trees
Total Accepted: 11242 Total Submissions: 31688My SubmissionsGiven 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,然后左右两边方法数相乘。但这样会出现重复--没考虑周全;
最后是纯数字的运算
My code:
public class Solution {
public int numTrees(int n) {
if(n<=0)
return 1;
if(n==1)
return 1;
int[] s = new int[n+1];
s[0]=1;
s[1]=1;
for(int i = 2; i <= n ; i++){
for(int j=0;j<i;j++){
s[i]+=s[j]*s[i-j-1];
}
}
return s[n];
}
}
别人的思路:
[Thoughts]
这题想了好久才想清楚。其实如果把上例的顺序改一下,就可以看出规律了。
1 1 2 3 3
\ \ / \ / /
3 2 1 3 2 1
/ \ / \
2 3 1 2
比如,以1为根的树有几个,完全取决于有二个元素的子树有几种。同理,2为根的子树取决于一个元素的子树有几个。以3为根的情况,则与1相同。
定义Count[i] 为以[0,i]能产生的Unique Binary Tree的数目,
如果数组为空,毫无疑问,只有一种BST,即空树,
Count[0] =1
如果数组仅有一个元素{1},只有一种BST,单个节点
Count[1] = 1
如果数组有两个元素{1,2}, 那么有如下两种可能
1 2
\ /
2 1
Count[2] = Count[0] * Count[1] (1为根的情况)
+ Count[1] * Count[0] (2为根的情况。
再看一遍三个元素的数组,可以发现BST的取值方式如下:
Count[3] = Count[0]*Count[2] (1为根的情况)
+ Count[1]*Count[1] (2为根的情况)
+ Count[2]*Count[0] (3为根的情况)
所以,由此观察,可以得出Count的递推公式为
Count[i] = ∑ Count[0...k] * [ k+1....i] 0<=k<i-1
问题至此划归为一维动态规划。
[Code]
1: int numTrees(int n) { 2: vector<int> count(n+1, 0); 3: count[0] =1; 4: count[1] =1; 5: for(int i =2; i<=n; i++) 6: { 7: for(int j =0; j<i; j++) 8: { 9: count[i] += count[j]*count[i-j-1]; 10: } 11: } 12: return count[n]; 13: }
[Note]
这是很有意思的一个题。刚拿到这题的时候,完全不知道从那下手,因为对于BST是否Unique,很难判断。最后引入了一个条件以后,立即就清晰了,即
当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性:
以i为根节点的树,其左子树由[0, i-1]构成, 其右子树由[i+1, n]构成。
- leetcode 难题 Unique Binary Search Trees
- LeetCode: Unique Binary Search Trees
- LeetCode : Unique Binary Search Trees
- [Leetcode] Unique Binary Search Trees
- [LeetCode]Unique Binary Search Trees
- LeetCode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode-Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees
- LeetCode - Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- 【Leetcode】Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- Leetcode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- FZU 2153 A simple geometric problems 凸包 + DP
- gdal_translate 不识别 GMT
- C# Color Name Table C#颜色和名称样式对照表
- spring学习笔记8——事务管理
- 【风宇冲】Unity3D教程宝典之插件篇:Unity3D插件详细评测及教学下载
- leetcode 难题 Unique Binary Search Trees
- Where is the Marble
- 单片机复习程序例举005 -- DS1302时钟芯片
- drupal7自定义输出节点内容($content里的每一个字段)
- POJ3104_DRYING_二分
- Android记事本开发之SQLite数据库实现
- CC2530与zigbee学习笔记の初识zigbee(3)
- python进阶七_文件操作(一)
- 005_013 Python 寻找子序列 字符串应该用find 否则用KMP