当前位置:网站首页>LeetCode_96_不同的二叉搜索树
LeetCode_96_不同的二叉搜索树
2022-07-28 17:05:00 【Fitz1318】
题目链接
题目描述
给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。
示例 1:

输入:n = 3
输出:5
示例 2:
输入:n = 1
输出:1
提示:
1 <= n <= 19
解题思路
动态规划法
首先明确一下二叉搜索树的定义:它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
以示例1为例子,dp[3]就是以元素1为根节点的二叉搜索树数量+元素2为根节点的数量+元素3为根节点的数量。并且根据二叉搜索树的定义,可以有如下总结:
- 1为根节点的数量 = 左子树有0个元素的数量 * 右子树有2个元素的数量
- 2为根节点的数量 = 左子树有1个元素的数量 * 右子树有1个元素的数量
- 3为根节点的数量 = 左子树有2个元素的数量 * 右子树有0个元素的数量
- 重点:有2个元素的数量为
dp[2],有1个元素的数量为dp[1]
因此可以得出dp[3] = dp[0] * dp[2] + dp[1] * dp[1] + dp[2] * dp[0],归纳一下可以得到
dp[i] += dp[j-1] * dp[i-j]
其中j相当于根节点,从1遍历到i为止.j-1为j为根节点的左子树节点数量,i-j为右子树节点数量
AC代码
class Solution {
public int numTrees(int n) {
if(n == 1){
return 1;
}
int[] dp = new int[n+1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <=i ; j++) {
dp[i] += dp[j-1] * dp[i-j];
}
}
return dp[n];
}
}
边栏推荐
- MongoDB初始化
- 微信公众号授权登录后报redirect_uri参数错误的问题
- Live broadcast starrocks technology insider: low base global dictionary optimization
- What are the conditions for zero foundation learning software testing?
- Docker搭建Mysql主从复制
- UE5 GAS 学习笔记 1.10 预测(Prediction)
- Mqtt over quic: the next generation Internet of things standard protocol injects new impetus into the message transmission scenario
- What skills do you need to master when learning software testing zero foundation?
- Go的sleep
- VSC上写Go出现expected ‘package‘, found ‘EOF‘
猜你喜欢

苹果开发完整的苹果证书与描述文件创建流程

连线:谁拥有未来的艺术?OpenAI允许Dall-E用户将作品商用化,目前而言

Introduction to oscilloscope

微信公众号授权登录后报redirect_uri参数错误的问题

天线的主要参数介绍

Introduction to CC cable of USB type-C

直播|StarRocks 技术内幕 :低基数全局字典优化

Five key considerations for network security budget planning in 2023

高德地图实现自定义小蓝点 自定义点标记 绘制多边形/圆形区域 根据地图的移动显示或者隐藏自定义点标记的相关实现

.net WCF wf4.5 state machine, bookmark and persistence
随机推荐
Ue5 gas learning notes 0.2 configuration plug-in
solidity的modifier修饰器的_;
高德地图实现自定义小蓝点 自定义点标记 绘制多边形/圆形区域 根据地图的移动显示或者隐藏自定义点标记的相关实现
Food safety | will the salt content of bread exceed the standard? A few tips to teach you to eat bread correctly!
Detailed explanation of oscilloscope parameters
苹果开发完整的苹果证书与描述文件创建流程
Brief introduction to the principle of spectrometer I
solidity的require报错
Five key considerations for network security budget planning in 2023
LeetCode79题 方法一:深度搜索
Mysql操作大全
MongoDB初始化操作
.net swagger
What is the employment prospect of software testing?
Mongodb create index
insight! Baidu pushed redis ceiling notes, which was originally understood by the database
天线的主要参数介绍
MySQL advanced mvcc (ultra detailed collation)
天线的原理、分类及要求
Advanced Design System(ADS)2009 射频仿真入门