当前位置:网站首页>leetcode96不同的二叉搜索樹
leetcode96不同的二叉搜索樹
2022-07-02 00:00:00 【瀛臺夜雪】
leetcode96:不同的二叉搜索樹
題目描述
給你一個整數 n ,求恰由 n 個節點組成且節點值從 1 到 n 互不相同的 二叉搜索樹 有多少種?返回滿足題意的二叉搜索樹的種數。
輸入輸出樣例

輸入:n = 3
輸出:5
輸入:n = 1
輸出:1
算法一:使用動態規劃
//二叉搜索樹的定義:若其左子樹不為空,則左子樹上所有的結點的值均小於他的根結點,若他的右子樹不空,則右子樹上所有的節點的值均大於他的根節點的值
//其左右子樹也為二叉查找樹
int numTrees(int n)
{
//建立動態規劃數組
vector<int>dp(n+1,0);
//設定初始條件
dp[0]=1;
dp[1]=1;
//設定轉換的方程
for(int i=2;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
dp[i]+=dp[j-1]*dp[i-j];
}
}
return dp[n];
}
算法二:使用格蘭數的定義
//卡塔蘭數
int numTrees2(int n)
{
long long c=1;
for(int i=0;i<n;i++)
{
c=c*2*(2*i+1)/(i+2);
}
return (int)c;
}
边栏推荐
- Door level modeling - after class exercises
- E-commerce RPA robot helps brand e-commerce to achieve high traffic
- 【QT】QtCreator卸载与安装(非正常状态)
- RPA tutorial 01: Excel automation from introduction to practice
- Windows10 install WSL (I) (wslregisterdistribution error)
- TS initial use, TS type
- 2021 robocom world robot developer competition - semi finals of higher vocational group
- S32Kxxx bootloader之UDS bootloader
- Key points and difficulties of the course "information content security" at Harbin Institute of Technology
- [QT] QT cannot find a solution to the compiler using msvc2017
猜你喜欢
![[QT] solve the problem that QT MSVC 2017 cannot compile](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[QT] solve the problem that QT MSVC 2017 cannot compile

Using uni simple router, dynamically pass parameters typeerror: cannot convert undefined or null to object

Review data desensitization system

Multi table operation - one to one, one to many and many to many
![Jielizhi, production line assembly link [chapter]](/img/1d/d1736fad33c428e61f450aad512ce0.png)
Jielizhi, production line assembly link [chapter]
![[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler

LDR6035智能蓝牙音响可对手机设备持续充放电方案
![Various global files related to [.Net core] program](/img/89/32623abf30d3dc92a3cdb1710a624f.png)
Various global files related to [.Net core] program
Linux CentOS7安装Oracle11g的超完美新手教程

华为HMS Core携手超图为三维GIS注入新动能
随机推荐
[QT] test whether QT can connect to the database
How excel opens CSV files with more than one million lines
安全协议重点
Is there a piece of code that makes you convinced by human wisdom
USB-IF协会与各种接口的由来
Is it safe to buy funds on Great Wall Securities?
const // It is a const object...class nullptr_t
攻防演练复盘
使用 pair 做 unordered_map 的键值
PostgreSQL notes (10) dynamically execute syntax parsing process
在代码中使用SqlCommand对象
Reproduction process and problems of analog transformer (ICLR 2022 Spotlight)
Timer和ScheduledThreadPoolExecutor的区别
【CMake】Qt creator 里面的 cmake 配置
Iota in golang
Windows installation WSL (II)
PostgreSQL source code (57) why is the performance gap so large in hot update?
Shell process control
在证券账户上买基金安全吗?哪里可以买基金
Three methods of finding inverse numbers