【leetcode】 Unique Binary Search Trees
2015-06-23 22:51
776 查看
From : https://leetcode.com/problems/unique-binary-search-trees/
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.
任选一个结点作为根结点,那么这棵树的组合为其左边树的组合数目乘以右边的组合数目,即
num[i] =
Σ num[k-1]*num[i-k] (1<=k<=i)
那么从小到大求可以依次求出num[i[, 最后返回num
即可。
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
任选一个结点作为根结点,那么这棵树的组合为其左边树的组合数目乘以右边的组合数目,即
num[i] =
Σ num[k-1]*num[i-k] (1<=k<=i)
那么从小到大求可以依次求出num[i[, 最后返回num
即可。
class Solution { public: int numTrees(int n) { if(n < 1) return 0; if(n < 3) return n; vector<int> num(n+1); num[0] = 1; num[1] = 1; num[2] = 2; for(int i=3; i<=n; i++){ for(int j=1; j<=i; j++) num[i] += num[j-1]*num[i-j]; } return num ; } };
public class Solution { public int numTrees(int n) { if (n < 1) { return 0; } if (n < 3) { return n; } int[] num = new int[n + 1]; num[0] = 1; num[1] = 1; num[2] = 2; for (int i = 3; i <= n; i++) { // length = i for (int j = 1; j <= i; j++) { // root is j num[i] += num[j - 1] * num[i - j]; } } return num ; } }
相关文章推荐
- hdu 1509 Windows Message Queue
- 【easuyi】---easyui中的验证validatebox自定义
- 构建基于IBM BlueMix的PHP网站
- 6.23
- poj 2031 Building a Space Station 【最小生成树 prime】
- 用block将UIAlertView与UIActionSheet统一起来
- UIStepper
- 程序员们有福了:独立于GUI的Java应用框架 Reflex 诞生了!
- leetcode-52-N-Queens II
- UIEdgeInsetsMake 和 UIEdgeInsetsMake
- QuerySyntaxException
- 合并流SequenceInputStream
- 黑马程序员--NSArray,NSString,NSSet,NSDictionary,NSNumber,NSValue 及其可变(NSMutable..)
- 解决 An AnnotationConfiguration instance is required to use
- UITableViewCell里面separator的设置
- C#.NET Request相关操作
- UIScrollView
- 关于iOS中UITableView下拉距离短刷新没事,下拉距离长就会崩溃的问题解决方案
- Uip + Stm32移植问题总结(转)
- 基于IBM Bluemix开发微信公共账号应用