【一天一道LeetCode】#96. Unique Binary Search Trees
2016-06-19 14:53
465 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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.
(二)解题
题目大意:给定一个数n,找出1~n组成的二叉搜索树的个数!可以参考【一天一道LeetCode】#95. Unique Binary Search Trees II
如果单单求个数的话,可以简化。
n=1时,num=1;n=2时,num=2;n=3时,num=5!
可以找出规律,num[i] = num[left]*num[right]!i从1取到n,就为num
的值。left和right为左右的节点个数。(节点个数小于等于1的时候记二叉搜索树个数为1)
以题目中的例子为例,取1为根节点,2,3组成的二叉搜索树个数为2(right),左边为1,所以1为根节点的二叉搜索树个数为2,依次可以算出,2为根节点时个数为1,3为根节点的个数为2,加起来为5!
class Solution { public: int numTrees(int n) { vector<int> num(n+1,-1);//存放i个节点存放的二叉搜索树个数 int ret = calNumTrees(1,n,num); return ret; } int calNumTrees(int start , int end , vector<int>& num) { if(num[end - start +1] != -1) return num[end - start +1]; if(start >= end) return 1;//当少于等于1个节点时,二叉搜索树个数记为1 int temp = 0; for(int i = start ; i <= end ; i++)//依次以1到n为根节点 { int left = calNumTrees(start,i-1,num);//左边二叉搜索树的个数 int right = calNumTrees(i+1,end,num);//右边二叉搜索树的个数 temp +=(left*right); } if(num[end - start +1] == -1) num[end-start+1] = temp;//num[i]存放1~i组成的个数 return temp; } };
相关文章推荐
- 重温5 UI开发
- UIView 中布局学习例子
- UITableView常见问题总结(二)
- IOS安全编码指南 Secure Coding Guide -- 02 Types of Security Vulnerabilities 下
- lucene prefixQuery
- Phoenix ,SQuirrel 与Hbase 搭建
- Arduino 卡片14红外遥控灯
- IOS UITableView 常见问题总结(-)
- “车城”项目问题总结之UITableView不同样式cell的运用
- build.xml
- thinkjs请求oss报错:RequestTimeTooSkewedError:
- 队列queue
- lucene query
- [LeetCode] Count Numbers with Unique Digits
- JAVA--019 GUI
- UIView 中简单的九宫格
- Arduino 卡片13自制风扇
- Arduino的程序烧录
- 应用服务器性能优化 之 消息队列(MQ:Message Queue)
- UGUI如何判断鼠标是否在UI上