当前位置:网站首页>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];
}
}
边栏推荐
- 天线的原理、分类及要求
- Go并发详解之一
- Tcp/ip detailed diagram
- UE5 GAS 学习笔记0.2配置插件
- Cout.write learning
- Six countries in Europe and the United States launched an express line product to optimize the "end-to-end" performance service on the 5th
- Huawei ZTE lost the lawsuit in the UK and will be banned if it does not pay the patent licensing fee!
- Advanced Design System(ADS)2009 射频仿真入门
- Details of iptables firewall
- 连线:谁拥有未来的艺术?OpenAI允许Dall-E用户将作品商用化,目前而言
猜你喜欢

Cloud container and cloud native

Golang并发模型之

ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法

Introduction to main parameters of antenna

Wired: who owns the art of the future? Openai allows dall-e users to commercialize their works. At present

Brief introduction to the principle of spectrometer II

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

.net WCF wf4.5 state machine, bookmark and persistence

Random talk on GIS data (VI) - projection coordinate system

SQL Server stuff and for XML path
随机推荐
UE5 GAS 学习笔记 1.6 技能Gameplay Ability
从 SRE 看 DevOps 建设
UE5 GAS 学习笔记8.0参考资料
Brief introduction to the principle of spectrometer II
What role does low code play in the digital transformation?
Multithreading and high concurrency -- source code analysis AQS principle
Go并发详解之一
Introduction to USB type-C PD fast charging
Power adapter global definition
TCP/IP详细图解
solidity转账函数的实现(基于transfer)
UE5 GAS 学习笔记 1.3属性Attribute
DC simulation example of ADS simulation
频谱仪原理简介一
Huawei ZTE lost the lawsuit in the UK and will be banned if it does not pay the patent licensing fee!
实验楼----PHP大法
Devops in digital transformation -- flexible cooperation
Syntax error: non declaration statement outside function bodygo and syntax error: unexpected {, expect
Brief introduction: basic principle of srv6
食品安全 | 面包含盐量也会超标?几招教你正确吃面包!