LeetCode OJ:Unique Binary Search Trees(唯一二叉搜索树)
2015-10-27 11:38
531 查看
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.
一开始是想用递归解决,但看了标签是dp问题,就想了一下, 数目为k的bst,其每个 0 ~ k - 1都可以分成两个区间, 然后又可以生成bst, 所以k的bst种类数等于取k左侧与右侧可划分成bst的乘机的总和,额,有点绕口额,代码清晰一点, 看代码:
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
一开始是想用递归解决,但看了标签是dp问题,就想了一下, 数目为k的bst,其每个 0 ~ k - 1都可以分成两个区间, 然后又可以生成bst, 所以k的bst种类数等于取k左侧与右侧可划分成bst的乘机的总和,额,有点绕口额,代码清晰一点, 看代码:
class Solution { public: int numTrees(int n) { vector<int> ret; if(n == 0) return 0; ret.reserve(n + 1); ret[0] = 1; for(int i = 1; i <= n; ++i){ if(i < 3){ ret[i] = i; continue; } for(int j = 0; j < i; ++j){ ret[i] += ret[j] * ret[i - j - 1]; } } return ret ; } };
相关文章推荐
- Virtualbox WDDM之DxgkDdiQueryAdapterInfo
- IOS--关于UIViewController添加UINavigationBar的详细实现方法
- UIScrollView常见属性
- 虚拟主机配置
- 深入浅出Cocoa多线程编程之block与dispatch quene
- Image Sampling and Nyquist Theorem (summary)
- UITextField+Category
- IOS UI Label的一些用法
- UIViewUILabel
- easyUI导出excel文件 提供下载功能
- Permutation Sequence
- UILabel
- UIVisualEffectView - initWithEffect
- UICollectionView的使用和布局方法
- UVA 11538-Chess Queen简单排列组合
- UITableView中用xib实现的cell中的View点击后View消失
- Android更新UI的两种方法——handler与runOnUiThread()
- UITableView中Lable自动换行,Cell自动适应高度
- 【HDOJ】【1005】Number Sequence
- UIBezierPath + bezierPathWithArcCenter