5.3.1 Unique Binary Sear Trees
2015-06-09 14:13
381 查看
Notes: | |
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 | |
Solution: dp. | |
*/ |
n=0,f(0)=0;
n=1,f(1)=1;
n=2,f(2)=f(0)*f(1)+f(1)*f(0)=2;
n=3,f(3)=f(0)*f(2)+f(1)*f(1)+f(2)*f(0)=5;
所以
class Solution { public: int numTrees(int n) { return numTrees_2(n); } int numTrees_1(int n) { int dp[n+1]; memset(dp, 0, sizeof(dp)); dp[0] = 1; for (int i = 1; i <= n; ++i) for (int j = 0; j < i; j++) dp[i] += dp[j] * dp[i-j-1]; return dp ; } int numTrees_2(int n) { if (n < 0) return 0; vector<int> dp(n+1, 0); dp[0] = 1; dp[1] = 1; for(int i = 2;i <= n; ++i){ dp[i] = dp[i-1] * (4 * i - 2)/(i + 1); } return dp ; } };
相关文章推荐
- 动态计算UITableViewCell高度详解
- UILabel的属性总结
- Dictionary的TryGetValue方法
- easyui动态表头 && 动态添加tabs
- VBox UUID already exists 问题处理
- 解决类型“System.Web.UI.UpdatePanel”不具有名为“Gridview”的公共属性,
- confluent integrated
- Windows Azure 系列-- Azure Queue的操作
- Win10 Build 10135官方32位镜像下载
- GuozhongCrawler系列教程 (5) TransactionRequest详解
- 优化UITableViewCell高度计算的那些事
- CodeIgniter学习笔记二:CI中的query_builder(AR)、连贯操作
- UITableView优化技巧
- Duilib技巧:背景图片平铺
- Java:String、StringBuffer和StringBuilder的区别
- uiview_animation
- request用法
- 动态计算UITableviewCell高度
- 【最小生成树+子集枚举】Uva1151 Buy or Build
- LeetCode51:N-Queens