4月份很快就过半了,最近都在看WPF,有点落伍了...本来想写一点读书笔记的,还没想好要怎么写。所以为了能够达到每月一篇博客的目标,今天先说一个LeetCode上的面试题:Unique Binary Search Trees

题目简单翻译过来就是说:

给定n个不同节点,问:可以构造出多少种异构的二叉搜索树。比方说n=3时有5种:

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

一般来说,遇到这种问题多半是找规律,总结出数学公式然后解决之。找规律前,首先要看我们有哪些可以利用的条件。

这里可用的条件很有限但也很明确:二叉搜索树。也就是其任意一部分二叉树都满足左子树节点都小于(或者大于)根节点;右子树节点都大于(或者小于)根节点。

我们已经有了n=3的结果,那么来看看n=4时的情况。我们知道,任何一个节点都可以成为一个根节点,那么:

  • 如果以1为树根,那么剩下的三个节点都分布在该树的右子树上;
  • 如果以2为树根,那么节点1必然是其左子树上的唯一节点,而3、4只可能在其优节点上;
  • 如果以3为树根,那么节点2、3在其左子树上,而节点4是其右子树上的唯一节点;
  • 如果以4为树根,那么甚于节点都在其左子树上;

这个简单的分析过程很快就将规律呈现了出来!!

对于n=4的情况,其异构结果就是各种独立情况下,左子树和右子树异构方式的排列数之和。用公式表示就是:f(4) = f(0) * f(3) + f(1) * f(2) + f(2) * f(1) + f(3) * f(0)。整一个典型的递归实现。唯一需要考虑的点就是你需要缓存一下中间数据,因为f(2)和f(3)分别被调用了2次。

 class Solution {
public:
int numTrees(int n) {
static vector<int> cached(, );
if (n > cached.size())
{
cached.resize(n, );
} if ( == n)
{
return ;
} if (cached[n - ] != )
{
return cached[n - ];
}
else
{
for (int i = ; i < n; ++i)
{
cached[n - ] += numTrees(i) * numTrees(n - i - );
} return cached[n - ];
}
}
};

顺带因为打算以后要有Python,所以附带上Python的代码。刚开始学着写Python,写着有点难过...(有没有更好的写法?)

 class Solution:
# @return an integer
def numTrees(self, n):
if 0 == n:
return 1 cached = [1]
if n > len(cached):
result = 0;
for i in range(n):
index = n - i - 1 left_part_result = self.numTrees(i)
right_part_result = self.numTrees(index) result += left_part_result * right_part_result if index == len(cached):
cached[len(cached):] = [right_part_result] cached[len(cached):] = [result] return result
else:
return cached[n - 1];

这题目的背景是一个称之为Catalan Number的数。也可以参看百度百科。通过了解Catalan Number,我们会发现他的诸多应用。比方说凸多边形的最优三角划分就是这个问题的拓展。

LeetCode之Unique Binry Search Trees的更多相关文章

  1. [leetcode]95. Unique Binary Search Trees II给定节点形成不同BST的集合

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

  2. [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆

    Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...

  3. Java for LeetCode 095 Unique Binary Search Trees II

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

  4. [LeetCode] 95. Unique Binary Search Trees II 唯一二叉搜索树 II

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

  5. [LeetCode] 96. Unique Binary Search Trees 唯一二叉搜索树

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

  6. [LeetCode] 96. Unique Binary Search Trees(给定一个数字n,有多少个唯一二叉搜索树) ☆☆☆

    [Leetcode] Unique binary search trees 唯一二叉搜索树 Unique Binary Search Trees leetcode java 描述 Given n, h ...

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

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

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

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

  9. 【leetcode】Unique Binary Search Trees

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

随机推荐

  1. angularjs的$on、$emit、$broadcast

    如何在作用域之间通信呢? 1.创建一个单例服务,然后通过这个服务处理所有子作用域的通信. 2.通过作用域中的事件处理通信.但是这种方法有一些限制:例如,你并不能广泛的将事件传播到所有监控的作用域中.你 ...

  2. 为什么说invalidate()不能直接在线程中调用

      1.为什么说invalidate()不能直接在线程中调用?2.它是怎么违背单线程的?3.Android ui为什么说不是线程安全的?4.android ui操作为什么一定要在UI线程中执行? 1. ...

  3. c语言的continue

    continue 是跳过此次循环的剩下部分,直接进入下个循环.

  4. ubuntu apt-get 时 Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

    sudo cp /etc/apt/sources.list ~/ sudo wget "http://pastebin.com/raw.php?i=uzhrtg5M" -O /et ...

  5. Oracle安装时OracleMTSRecoveryService找不到

    电脑重做系统之后再安装oracle过程中出现一个问题,说OracleMTSRecoveryService找不到指定的目录文件,卸载重装还是没有改变,挣了半天终于找到怎么更改了,打开注册表编辑器,SYS ...

  6. Redis ConnectionException

    JAVA 远程链接Redis服务失败,错误信息如下: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a ...

  7. MySQL 解压包 安装

    1.解压 2.配置mysql bin的环境变量 3.配置my-defalue.ini 配置文件 或自己建立一个my.ini文件 [mysqld] basedir=F:\mysql\mysql-5.6. ...

  8. this

    JavaScript 中的 this ! 2016-12-28 vvv阿城 JavaScript 转自  https://qiutc.me/post/this-this-this-in-javascr ...

  9. PageRank理论与实践及用户评分应用PeopleRank算法

    PageRank,网页排名,又称网页级别.Google左侧排名或佩奇排名,是一种由根据网页之间相互的超链接计算的技术,而作为网页排名的要素之一. Google用它来体现网页的相关性和重要性,在搜索引擎 ...

  10. asp.net登录时验证码的制作与验证

    1.新建一个页面,ImageCode.aspx 2.在Page_Load中添加如下代码 string tmp = RndNum(4); HttpCookie a = new HttpCookie(&q ...