LeetCode 96:Unique Binary Search Trees
2015-12-31 16:35
513 查看
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.
Subscribe to see which companies asked this question
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
Subscribe to see which companies asked this question
//由1,2,3,...,n构建的二叉查找树,以i为根节点,左子树由[1,i-1]构成,其右子树由[i+1,n]构成。 //定义f(i)为以[1,i]能产生的Unique Binary Search Tree的数目 //若数组为空,则只有一种BST,即空树,f(0)=1; //若数组仅有一个元素1,则只有一种BST,单个节点,f(1)=1; //若数组有两个元素1,2,则有两种可能,f(2)=f(0)*f(1)+f(1)*f(0); //若数组有三个元素1,2,3,则有f(3)=f(0)*f(2)+f(1)*f(1)+f(2)*f(0) //由此可以得到递推公式:f(i)=f(0)*f(i-1)+...+f(k-1)*f(i-k)+...+f(i-1)*f(0) //利用一维动态规划来求解 class Solution { public: int numTrees(int n) { vector<int> f(n+1,0); //n+1个int型元素,每个都初始化为0 f[0] = 1; f[1] = 1; for (int i = 2; i <= n; ++i){ for (int k = 1; k <= i; ++k) f[i] = f[i] + f[k - 1] * f[i - k]; } return f ; } };
相关文章推荐
- easyui样式及js导入顺序及刷新回车的问题
- 基于Silverlight/XAML开发嵌入式系统WinCE下应用程序UI
- IOS 16进制颜色字符串转UIColor
- Android多语言适配values文件夹命名
- easyui合并行(同列内容合并)
- IOS UI-滚动视图(UIScrollView)
- iOS UI-文本视图(UITextView)
- poj 1947 Rebuilding Roads 树形背包 ★
- mosquitto 管理常用命令
- UIScrollView配合定时器和手动实现图片轮播无限循环
- PowerBuilder
- 自定义UITableViewCell上的按钮点击事件处理
- 初识android自定义UI
- iOS 代码实现获得应用的版本号(Version/Build)
- Preparing to build session factory with filters : {}
- Arduino和Android通过OTG 通信
- ubuntu下使用quick2wire控制RespberryPi2的I2C
- 【iOS笔记】Xcode中Build Configuration配置使用
- ${pageContext.request.contextPath} JSP取得绝对路径
- uitableView自适应大小