LeetCode: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.

   1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

分析:依次把每个节点作为根节点,左边节点作为左子树,右边节点作为右子树,那么总的数目等于左子树数目*右子树数目,实际只要求出前半部分节点作为根节点的树的数目,然后乘以2(奇数个节点还要加上中间节点作为根的二叉树数目)

递归代码:为了避免重复计算子问题,用数组保存已经计算好的结果

 class Solution {
public:
int numTrees(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int nums[n+]; //nums[i]表示i个节点的二叉查找树的数目
memset(nums, , sizeof(nums));
return numTreesRecur(n, nums);
}
int numTreesRecur(int n, int nums[])
{
if(nums[n] != )return nums[n];
if(n == ){nums[] = ; return ;}
int tmp = (n>>);
for(int i = ; i <= tmp; i++)
{
int left,right;
if(nums[i-])left = nums[i-];
else left = numTreesRecur(i-, nums);
if(nums[n-i])right = nums[n-i];
else right = numTreesRecur(n-i, nums);
nums[n] += left*right;
}
nums[n] <<= ;
if(n % != )
{
int val;
if(nums[tmp])val = nums[tmp];
else val = numTreesRecur(tmp, nums);
nums[n] += val*val;
}
return nums[n];
}
};

非递归代码:从0个节点的二叉查找树数目开始自底向上计算,dp方程为nums[i] = sum(nums[k-1]*nums[i-k]) (k = 1,2,3...i)

 class Solution {
public:
int numTrees(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int nums[n+]; //num[i]表示i个节点的二叉查找树数目
memset(nums, , sizeof(nums));
nums[] = ;
for(int i = ; i <= n; i++)
{
int tmp = (i>>);
for(int j = ; j <= tmp; j++)
nums[i] += nums[j-]*nums[i-j];
nums[i] <<= ;
if(i % != )
nums[i] += nums[tmp]*nums[tmp];
}
return nums[n];
}
};

LeetCode:Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

按照上一题的思路,我们不仅仅要保存i个节点对应的BST树的数目,还要保存所有的BST树,而且1、2、3和4、5、6虽然对应的BST数目和结构一样,但是BST树是不一样的,因为节点值不同。

我们用数组btrees[i][j][]保存节点i, i+1,...j-1,j构成的所有二叉树,从节点数目为1的的二叉树开始自底向上最后求得节点数目为n的所有二叉树                                                                               本文地址

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<vector<TreeNode*> > > btrees(n+, vector<vector<TreeNode*> >(n+, vector<TreeNode*>()));
for(int i = ; i <= n+; i++)
btrees[i][i-].push_back(NULL); //为了下面处理btrees[i][j]时 i > j的边界情况
for(int k = ; k <= n; k++)//k表示节点数目
for(int i = ; i <= n-k+; i++)//i表示起始节点
{
for(int rootval = i; rootval <= k+i-; rootval++)
{//求[i,i+1,...i+k-1]序列对应的所有BST树
for(int m = ; m < btrees[i][rootval-].size(); m++)//左子树
for(int n = ; n < btrees[rootval+][k+i-].size(); n++)//右子树
{
TreeNode *root = new TreeNode(rootval);
root->left = btrees[i][rootval-][m];
root->right = btrees[rootval+][k+i-][n];
btrees[i][k+i-].push_back(root);
}
}
}
return btrees[][n];
}
};

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3448569.html

LeetCode:Unique Binary Search Trees I II的更多相关文章

  1. [LeetCode] Unique Binary Search Trees II 独一无二的二叉搜索树之二

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  2. LeetCode: Unique Binary Search Trees II 解题报告

    Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search trees) ...

  3. leetcode -day28 Unique Binary Search Trees I II

    1.  Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search t ...

  4. LeetCode - Unique Binary Search Trees II

    题目: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. F ...

  5. Leetcode:Unique Binary Search Trees & Unique Binary Search Trees II

    Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees) that st ...

  6. [LeetCode] Unique Binary Search Trees 独一无二的二叉搜索树

    Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For examp ...

  7. Unique Binary Search Trees I & II

    Given n, how many structurally unique BSTs (binary search trees) that store values 1...n? Example Gi ...

  8. LeetCode——Unique Binary Search Trees II

    Question Given an integer n, generate all structurally unique BST's (binary search trees) that store ...

  9. [Leetcode] Unique binary search trees ii 唯一二叉搜索树

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

随机推荐

  1. System.Data.Entity 无法引用的问题

    最近刚学MVC,跟着网上的博客学习,发现代码中有这样一句: using System.Data; using System.Data.Entity; 我项目引用的时候,也引用了System.Data. ...

  2. UC 浏览器远程调试手机web网页记录

    浏览器远程调试插件有很多,本来要使用chrome浏览器的调试插件的,但是需要FQ才能使用(公司网络有限制,果断放弃),最终选择使用UC浏览器的. 其实UC官网插件使用已经介绍的很详细了,但是有几处坑需 ...

  3. 烂泥:【解决】Ubuntu下使用SSH连接centos系统很慢

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 这几天在Ubuntu下使用SSH连接centos系统,发现连接很慢.建议一个连接大约需要30s.很是坑爹,如下: 后来查询相关资料,发现这个是Ubunt ...

  4. 工作中常用的Linux命令:目录

    工作两三年,每天都和Linux打交道,但每每使用Linux命令的时候却会像提笔忘字般不知如何使用,常常查手册或到网上找资料.此系列文章主要是为了方便自己在使用命令时随时可查阅.鄙人才疏学浅,文中若有任 ...

  5. 解决ubuntu sudo not found command的问题

    将/etc/sudoers 中Defaults env_reset改成Defaults !env_reset取消掉对PATH变量的重置, 然后在/etc/bash.bashrc中最后添加alias s ...

  6. c# App.Config详解

    c# App.Config详解 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序. 配置文件的根 ...

  7. Virtual Box上安装CentOS7

    问题1:安装完没有桌面系统(Gnome或KDE)解答:安装的时候,软件选择为最小安装",更改该选择 问题2:开机提示Initial setup of CentOS Linux 7 (core ...

  8. 谷歌和HTTPS

    谷歌和HTTPS HTTPS被觉得是加强互联网安全的次要部分,而且使用广泛.google近来做了一份关于数据加密近况的陈述. 正在陈述的最新部分中,提到了google以及第三方构造对于数据加密所做的贡 ...

  9. Medial Queries的另一用法:实现IE hack的方法

    所谓Medial Queries就是媒体查询. 随着Responsive设计的流行,Medial Queries可算是越来越让人观注了.他可以让Web前端工程实现不同设备下的样式选择,让站点在不同的设 ...

  10. 字典树(Tire)模板

    #include<stdio.h> #include<string.h> #include<stdlib.h> struct node { node *ne[]; ...