博客
关于我
【LeetCode 中等题】49-不同的二叉搜索树
阅读量:294 次
发布时间:2019-03-01

本文共 1084 字,大约阅读时间需要 3 分钟。

题目描述:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?

示例:

输入: 3输出: 5解释:给定 n = 3, 一共有 5 种不同结构的二叉搜索树:   1         3     3      2      1    \       /     /      / \      \     3     2     1      1   3      2    /     /       \                 \   2     1         2                 3

解法1。假设n个节点存在二叉排序树的个数是G(n),令f(i)为以i为根的二叉搜索树的个数,即有:G(n) = f(1) + f(2) + f(3) + f(4) + ... + f(n)。n为根节点,当i为根节点时,其左子树节点个数为[1,2,3,...,i-1],右子树节点个数为[i+1,i+2,...n],所以当i为根节点时,其左子树节点个数为i-1个,右子树节点为n-i,而这左子树的可能排布方式有G(i-1)种,同理右子树的为G(n-i),即f(i) = G(i-1)*G(n-i),

上面两式可得:G(n) = G(0)*G(n-1)+G(1)*(n-2)+...+G(n-1)*G(0)

解题思路:假设n个节点存在二叉排序树的个数是G(n),1为根节点,2为根节点,...,n为根节点,当1为根节点时,其左子树节点个数为0,右子树节点个数为n-1,同理当2为根节点时,其左子树节点个数为1,右子树节点为n-2,所以可得G(n) = G(0)*G(n-1)+G(1)*(n-2)+...+G(n-1)*G(0)

class Solution(object):    def numTrees(self, n):        """        :type n: int        :rtype: int        """        # 用一个一维数组存储0-n的所有排布方式个数,自底向上计算出dp[n]并返回        dp = [0 for _ in range(n+1)]        dp[0] = 1        dp[1] = 1        for i in range(2,n+1):            for j in range(i):                dp[i] += dp[j]*dp[i-j-1]        return dp[n]

 

 

参考链接:

转载地址:http://tufo.baihongyu.com/

你可能感兴趣的文章
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用exec节点实现调用外部exe程序
查看>>
Node-RED中使用function函式节点实现数值计算(相加计算)
查看>>