lintcode: Unique Binary Search Trees
2016-04-03 21:51
651 查看
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
Have you met this question in a real interview?
Example
Given n = 3, there are a total of 5 unique BST's.
Tags
Have you met this question in a real interview?
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
Tags
class Solution { public: /** * @paramn n: An integer * @return: An integer */ int numTrees(int n) { // write your code here /* if (n==1 || n==0) return 1; static vector<int> dp(n+1); //因为loop从1到n, 所以设置 dp为 n+1 if (dp != 0) return dp ; int retVal = 0; for (int i=1; i<=n; i++) { if (i==1 || i==n) retVal += numTrees(n-1); else retVal += (numTrees(i-1)*numTrees(n-i)); } dp = retVal; return retVal; */ if (n == 1 || n == 0) return 1; vector<int> nums(n+1); nums[0] = 1; for (int i=1; i<=n; i++) { for (int j=1; j<=i; j++) { nums[i] += nums[j-1]*nums[i-j]; } } return nums ; } };
相关文章推荐
- [html][LigerUI]使用示例
- DELL DOSA 6.X 服务器引导光盘Dell Systems Build and Update Utility ISO下载地址
- IOS9 UIStackView简介
- DuiLib(4)——消息响应
- Android 入门三 UI界面
- 02-线性结构3 Pop Sequence
- request 和 response之间实现servlet线程非阻塞
- Liferay 6.1开发学习(四):Service Builder
- Android入门(五)UI-单位与尺寸、ListView
- Android入门(四)UI-创建自定义控件
- iOS UIVisualEffectView 为视图添加特殊毛玻璃的效果
- Providing Resources
- UI基础 - UINavigationController
- Vector , list 和 deque的区别
- UI基础 - UITabBarController
- Android UI 同步
- Qt Quick无边框窗口
- 第65课:SparkSQL下Parquet深入进阶学习笔记
- Java [Leetcode 96]Unique Binary Search Trees
- 第64课:SparkSQL下Parquet的数据切分和压缩内幕详解学习笔记