当前位置:网站首页>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];
}
}
边栏推荐
- Implementation of solid transfer function (based on transfer)
- Noise of creative coding
- "Cloud strategy" will become an important pillar of enterprise digital transformation
- Ue5 gas learning notes 0.1 case Preview
- Golang 并发之锁
- Novice record: some small knowledge of mechanical keyboard
- 冒泡排序和相关视频
- Is the training institution of software testing reliable
- 腾讯汤道生:开源是产业互联网时代新的生产方式和协作模式
- ADS仿真 之 交流仿真和S参数仿真示例
猜你喜欢

NDK 系列(5):JNI 从入门到实践,爆肝万字详解!

Principle, classification and requirements of antenna

Mqtt over quic: the next generation Internet of things standard protocol injects new impetus into the message transmission scenario

深圳线下报名|StarRocks on AWS:如何对实时数仓进行极速统一分析

.net WCF WF4.5 状态机、书签与持久化

【译】创意编码之噪音

Introduction to main parameters of antenna

频谱分析仪的性能参数

Detailed explanation of network RJ45 interface

Multithreading and high concurrency -- source code analysis AQS principle
随机推荐
网络RJ45接口详解
The revenue of Shanghai silicon industry in the first half of the year was 850million yuan, an increase of 30.53% year on year! Various product certifications are accelerating
UE5 GAS 学习笔记 1.9 技能系统全局类(AbilitySystemGlobals)
MongoDB创建索引
Ue5 gas learning notes 0.2 configuration plug-in
冒泡排序和相关视频
VSC上写Go出现expected ‘package‘, found ‘EOF‘
SQL Server stuff and for XML path
Modifier modifier modifier of solidity _;
Go语言系列之日志库zap
Brief introduction: basic principle of srv6
ADS仿真 之 直流仿真示例
Digital torrent: resource reorganization and strategic conflict in enterprise transformation
欧美六国最快5日达 菜鸟推出快线产品 优化“端到端”履约服务
Go's walk library reports an error
UE5 GAS 学习笔记8.0参考资料
Go的walk库报错
Golang 并发之锁
Introduction to the principle of signal source
频谱仪原理简介二