Unique Binary Search Trees
2015-06-18 17:09
453 查看
Description:
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.
Code:
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
Code:
int numTrees(int n) { //f[i][j]表示数字i,i+1,...,j有多少棵不同的树 int f[MAX][MAX] = {0}; for (int i = 1; i <= n; ++i) {//只有一个节点的情况 f[i][i] = 1; } for (int i = 2; i<=n; ++i) {//有2,3,4,....n个元素的情况 for (int j = 1; j<=n-i+1; ++j ) { int m = j+i-1; //计算f[j][m]; //先考虑两端为根节点的情况 f[j][m] = f[j][m-1]+f[j+1][m]; for (int k = j+1; k <= m-1; ++k)//k表示以k为根节点,左边的数据为j...k-1,右边的数据为k+1,..,m f[j][m] += f[j][k-1] * f[k+1][m]; } } return f[1] ; }
相关文章推荐
- 百度ueditor上传图片时设置默认宽高度
- StringBuilder与StringBuffer的区别(转)
- 使用CAShapeLayer与UIBezierPath画出想要的图形
- SKTexure To UIImage,即 SpriteKit 截屏
- iOS开发-UISwipeGestureRecognizer滑动手势
- 织梦DedeCMS添加变量报错Request var not allow!的解决办法
- SeGue 多控制器跨界面传递数据原理
- Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
- adobe flash builder 4.6安装EGit
- Google I/O 2009 Make your Android UI Fast and Efficient
- Android 数据查询query函数参数解析
- 关于easyUI在子页面增加显示tabs的一个问题
- Hbuilder编辑器怎么用 使用方法(wap静态页面测试)
- UIScrollView增加回弹效果
- iOS UIButton 设置图片文字垂直排列
- win7怎么开启guest本地登录?
- 移动开发:dequeueReusableCellWithIdentifier的运行机制
- smart_stl::deque相关总结
- UIButton 详解
- UITextField详解