您的位置:首页 > 产品设计 > UI/UE

【一天一道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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: