[Leetcode] - 96 Unique Binary Search Trees
2015-10-03 15:36
477 查看
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) {
if (n <= 2) return n;
vector<int>nums(n + 1);
nums[0] = 1;
for (int i = 1; i <= n; ++i ) {
if (i < 3) {
nums[i] = i;
continue;
}
for (int j = 1; j <= i; ++j) {
nums[i] += nums[j - 1] * nums[i - j];
}
}
return nums
;
}
};
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) {
if (n <= 2) return n;
vector<int>nums(n + 1);
nums[0] = 1;
for (int i = 1; i <= n; ++i ) {
if (i < 3) {
nums[i] = i;
continue;
}
for (int j = 1; j <= i; ++j) {
nums[i] += nums[j - 1] * nums[i - j];
}
}
return nums
;
}
};
相关文章推荐
- IOS初学笔记UI--UIView
- JPA主键生成策略
- HDU 1815, POJ 2749 Building roads(2-sat)
- UIScrollView与NSTimer计时器、分页指示器控件的使用
- UICollectionView的使用
- hdu5493 Queue 线段树
- note: please rebuild precompiled header ..... /UIKit-2DYE2I2D1B3GL.pcm 解决方案
- 69. Sqrt(x) (Divide-and-Conquer)
- java gui案例开发
- Longest Consecutive Sequence
- 109. Convert Sorted List to Binary Search Tree (List; Divide-and-Conquer, dfs)
- 108.Convert Sorted Array to Binary Search Tree(Array; Divide-and-Conquer, dfs)
- 条款20:宁以pass-by-reference-to-const替换pass-by-value
- servlet中response和request的字符编码问题
- MAVEN ERROR: unable to find valid certification path to requested target 解决办法
- SuiShenJi项目_dialog to Activity动画
- SuiShenJi项目_按钮等背景样式
- SuiShenJi项目_Activity跳转、传值
- SuiShenJi项目_计算器逻辑
- vnc连接kvm中的guest窗口一闪而过