[leetcode]96. Unique Binary Search Trees
2016-07-12 22:34
513 查看
题目:
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.
分析:任意一个节点都可以作为根节点,比他小的构成左子树,比他大的构成右子树。此题用递推。
代码:
class Solution {
public:
int numTrees(int n) {
vector<int> nums(n+1,0);
nums[0]=1;
nums[1]=1;
for(int i=2;i<=n;i++){
for(int j=0;j<i;j++){
nums[i]+=nums[j]*nums[i-j-1];
}
}
return nums
;
}
};
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
分析:任意一个节点都可以作为根节点,比他小的构成左子树,比他大的构成右子树。此题用递推。
代码:
class Solution {
public:
int numTrees(int n) {
vector<int> nums(n+1,0);
nums[0]=1;
nums[1]=1;
for(int i=2;i<=n;i++){
for(int j=0;j<i;j++){
nums[i]+=nums[j]*nums[i-j-1];
}
}
return nums
;
}
};
相关文章推荐
- IPhone 自定义 UITableViewCell 行缩进,使cell进入编辑状态时不右移
- HwUI,CMS管理系统模板,漂亮,简单,兼容好
- Android 如何完美解决MenuItem偏移问题
- Friends and Subsequences(RMQ+二分||双端队列)
- UESTC 2016 Summer Training #1 Div.2 H - Queue (A) 贪心
- Android Studio官方文档之使用翻译编辑器本地化UI
- iOS 【UIKit-关于 UIImageView contentMode 属性设置无效】
- UESTC 2016 Summer Training #1 Div.2 L - Plus or Minus (A) dfs
- 225. Implement Stack using Queues
- TimeQuest API: 时钟约束
- UESTC 2016 Summer Training #1 Div.2 F - Mission in Amman (A) 动态维护(刷新:--、++)
- 解决Android Stuio 的Gradle sync failed: Gradle DSL method not found: 'android()'
- 在ideal中以equinox-SDK-Neon框架输出一个基于osgi的helloworld例子
- codeforces 361 D - Friends and Subsequences
- UESTC 2016 Summer Training #1 Div.2 E - Accepted Passwords 讨论
- HDU 1423 Greatest Common Increasing Subsequence LCIS
- Duilib中各个类的简单介绍
- Fibonacci sequence
- WM_DESTROY,WM_CLOSE,WM_QUIT的联系与区别
- Duilib界面库 Demo实例XML编写规则 模仿QQ登录模块