leetCode(26):Unique Binary Search Trees 分类: leetCode 2015-06-23 14:09 155人阅读 评论(0) 收藏
2015-06-23 14:09
495 查看
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.
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
1)结构的总数和存储的n个有序数没有关系,即存放的是1,2,3或5、6、9结果都是一样的; 2)n=0\1时,结果都为1;n个有序数,取任何一个作为根结点,该值左边的为左子树,右边的为右子树, 在这种情况下,可能的结构总数为:左子树结构数*右子树结构数,所以原问题就被分解成了两个子问题; 3)将取n个有序数作为根结点的情况的结构问题相加,即可得到原问题的解,但应注意的是,如:1、2、3 取1或3作为根结点的情况,结构数是相同的,即具有对称性;那么也要考虑到奇偶性; 4)能够被分解成相同的子问题,自己就可以采用递归,本程序采用循环的方法。 */ int numTrees(int n) { vector<int> store; store.push_back(1); store.push_back(1); for(int i=2;i<=n;++i) { int tmp=0; for(int j=0;j<i/2;++j) { tmp+=2*store[i-1-j]*store[j]; } if(i%2) tmp+=store[i/2]*store[i/2]; store.push_back(tmp); } return store ; }
相关文章推荐
- Longest Palindrome Subsequence
- 使用.bat文件运行ant的build.xml
- arm交叉编译器gnueabi、none-eabi、arm-eabi、gnueabihf、gnueabi区别
- 构建验证测试BVT--Build Verification Test
- 在NGUI中高效优化UIScrollView之UIWrapContent的简介以及使用
- debug - UITextField 输入完跳入下一field,按钮变化
- EasyUI-解决EasyUI 加载两次url的问题
- [mysql]ERROR 1364 (HY000): Field 'ssl_cipher' doesn't have a default value 解决方法
- 最新全功能DNV sesam suite 2013 Full 1CD包含新的 DeepC 、GeniE和HydroD模块.
- JDBC实例之—手机号码归属地查询(GUI版本)
- UIView的背景颜色
- arduino 呼吸灯
- UIView常见方法
- easyui datagrid中如何展示图片
- 【NGUI】实现淡入淡出提示框功能
- UIView的常见属性
- Flexisign Pro v10.5.1 Build 1806-ISO 1DVD(电脑切割系统)
- Sokkia Mapsuite+ v3.0 build 304-ISO 1CD(勘探测绘软件)
- UI--仿IOS控件之ActionSheet样式 and more..
- UE4学习之材质系统初探