当前位置:网站首页>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];
}
}
边栏推荐
- UE5 GAS 学习笔记 1.9 技能系统全局类(AbilitySystemGlobals)
- 初识结构体
- Brief introduction: basic principle of srv6
- There is a special cryptology language called asn.1
- What are the conditions for zero foundation learning software testing?
- Is it difficult for novices to change careers through self-study software testing?
- UE5 GAS 学习笔记 1.10 预测(Prediction)
- 示波器探头详解
- MongoDB初始化操作
- syntax error: non-declaration statement outside function bodygo 和 syntax error: unexpected {, expect
猜你喜欢

顿悟!百度强推的Redis天花板笔记,原来数据库是这样理解的

Live broadcast starrocks technology insider: low base global dictionary optimization

Introduction to CC cable of USB type-C

Brief introduction: basic principle of srv6

【译】创意编码之噪音

DC simulation example of ADS simulation

TCP/IP详细图解

Introduction to the principle of signal source

Detailed explanation of network RJ45 interface

ADS仿真 之 交流仿真和S参数仿真示例
随机推荐
What skills do you need to master when learning software testing zero foundation?
syntax error: non-declaration statement outside function bodygo 和 syntax error: unexpected {, expect
Internet intelligence, how to define the next generation network transformation
冒泡排序和相关视频
MongoDB创建索引
VSC writes go, expected 'package' appears, found 'EOF‘
矢量网络分析仪(矢网)组成和原理简介
当Golang遇到高并发秒杀
Mongodb create index
Iptables configuration
What is the employment prospect of software testing?
.net swagger
UE5 GAS 学习笔记 1.2游戏标签
Detailed explanation of network RJ45 interface
GIS数据漫谈(六)— 投影坐标系统
Docker搭建Mysql主从复制
UE5 GAS 学习笔记 1.1能力系统组件Ability System Component
Go并发详解之一
What is the future of software testing?
Introduction to advanced design system (ads) 2009 RF simulation