当前位置:网站首页>leetcode刷题:动态规划07(不同的二叉搜索树)
leetcode刷题:动态规划07(不同的二叉搜索树)
2022-07-25 19:15:00 【涛涛英语学不进去】
96.不同的二叉搜索树
给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:

没做出来,研究题解最后做出来了。思路很简单。
当前dp[ i ]的值为以本树所有结点的每个结点都做一次头结点,左子树和右子树变化的乘积为总和, 比如以 j 为根结点,则比 j 小的数组成的左子树,有 j - 1 个数,也就是dp[ j - 1 ]种组合,比 j 大的数,一共 i - j 个,则右子树的数字有 i - j 个,共 dp [ i - j ]种变化。左右相乘,为当前 j 为结点的总变化,所有的总变化就是每个数都当一次头结点,所变化之和。
package com.programmercarl.dynamic;
/** * @ClassName NumTrees * @Descriotion TODO * @Author nitaotao * @Date 2022/7/25 17:00 * @Version 1.0 * https://leetcode.cn/problems/unique-binary-search-trees/ * 96. 不同的二叉搜索树 **/
public class NumTrees {
public int numTrees(int n) {
/** * 二叉搜索树,升序 * n>=1 */
if (n <= 2) {
return n;
}
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
// n>=1
for (int j = 1; j < i; j++) {
//dp[i]的每种可能性为以其中一个数为头结点,左子树的变法*右子树的变法
// 以 dp[j]为头结点
//左子树有j-1个 右子树有i-j个
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}

边栏推荐
- 小程序毕设作品之微信校园维修报修小程序毕业设计成品(6)开题答辩PPT
- 基础乐理之音程的度数
- 小程序毕设作品之微信校园维修报修小程序毕业设计成品(3)后台功能
- 微信小程序 26 播放音乐页的完善②
- 果链“围城”:傍上苹果,是一场甜蜜与苦楚交错的旅途
- Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 1)
- 歌曲转调之后和弦如何转换
- 一个函数中写多少行代码比较合适呢? 代码整洁之道
- 小程序毕设作品之微信校园维修报修小程序毕业设计成品(2)小程序功能
- 网上商城系统MySql数据库设计项目实战
猜你喜欢

这种动态规划你见过吗——状态机动态规划之股票问题(上)

Based on easycv to reproduce Detr and dab-detr, the correct opening method of object query

Actual combat of MySQL database design project of online mall system

Real estate enterprises have launched a "war of guarantee"

基于FPGA的1080P 60Hz BT1120接口调试过程记录

SQL Server 2019 installation tutorial

微信小程序 29 热搜榜的完善②

Pymoo learning (6): termination conditions

SQL Server 2019 安装教程

Talk about 11 tips for interface performance optimization
随机推荐
GDB help
【HDLBits 刷题】Verilog Language(3)Modules: Hierarchy 部分
The second "future Cup" knowledge map championship was officially launched
How to change the chords after the tune of the song is changed
微信小程序 26 播放音乐页的完善②
Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
李宏毅《机器学习》丨1. Introduction of this course(机器学习介绍)
Gan, why ".Length! == 3??
网上商城系统MySql数据库设计项目实战
PyQt5单击QTableView垂直表头verticalHeader获取行数据以及单击单元格获取行数据操作
Hongmeng - Damiao computing Sketchpad - Introduction
Ping command details [easy to understand]
鸿蒙-大喵计算画板-视频
Telnet installation and telnet (correct password) cannot log in!
HTTP缓存通天篇,可能有你想要的
小程序毕设作品之微信校园维修报修小程序毕业设计成品(8)毕业设计论文模板
Baklib: make excellent product instruction manual
微信小程序 27 进度条的动态实现和搜索框、热搜榜的静态搭建
PHP等于==和恒等于===的区别
[open source project] stm32c8t6 + ADC signal acquisition + OLED waveform display