当前位置:网站首页>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];
}
}
边栏推荐
- insight! Baidu pushed redis ceiling notes, which was originally understood by the database
- 多线程与高并发—— 源码解析 AQS 原理
- Experimental building - PHP Dafa
- Software testing needs more and more talents, but fewer people are on the road of testing?
- UE5 GAS 学习笔记 1.6 技能Gameplay Ability
- Internet intelligence, how to define the next generation network transformation
- Iptables configuration
- Is it difficult for novices to change careers through self-study software testing?
- 矢量网络分析仪(矢网)的校准
- MongoDB创建索引
猜你喜欢

频谱仪原理简介二

DC-DC开关电源

It is said that software testing is the worst in the IT industry. Is that so?

一文简述:SRv6基本原理

矢量网络分析仪(矢网)组成和原理简介
![Summer Challenge [FFH] JS custom component: DIY a keyboard that can be used at any time! (I)](/img/92/abc5c4e7aee3c65aa0f62fc699b4df.jpg)
Summer Challenge [FFH] JS custom component: DIY a keyboard that can be used at any time! (I)

多线程与高并发—— 源码解析 AQS 原理

NDK series (5): from introduction to practice, JNI explodes the liver and explains everything in detail!

Detailed explanation of oscilloscope parameters

Introduction to USB type-C PD fast charging
随机推荐
ADS仿真 之 交流仿真和S参数仿真示例
UE5 GAS 学习笔记 1.6 技能Gameplay Ability
UE5 GAS 学习笔记 1.10 预测(Prediction)
Go语言系列之日志库zap
示波器参数详解
高温天气户外活动有讲究!市民盛夏健身安全指引来了
solidity的require报错
网络RJ45接口详解
【译】创意编码之噪音
一文简述:SRv6基本原理
Trial record of ModelBox end cloud collaborative AI development kit (rk3568) (III)
Seven steps, in-depth interpretation of data meaning
Random talk on GIS data (VI) - projection coordinate system
GIS数据漫谈(六)— 投影坐标系统
GO exe生成图标版本信息
明德生物:公司暂未有产品被列入WHO推荐清单
Huawei ZTE lost the lawsuit in the UK and will be banned if it does not pay the patent licensing fee!
MongoDB数据库复制表
数字化转型中的DevOps——弹性合作
Six countries in Europe and the United States launched an express line product to optimize the "end-to-end" performance service on the 5th