当前位置:网站首页>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;
}
边栏推荐
- MySQL: the difference between insert ignore, insert and replace
- How to solve the image pop-up problem when pycharm calls Matplotlib to draw
- Overview of edge calculation
- cookie、session、tooken
- Operate database transactions with jpatractionmanager
- 【C#】依赖注入及Autofac
- 写给当前及未来博士研究生一些建议整理分享
- [embedded system course design] a single key controls the LED light
- - Oui. Env. Fichier XXX, avec constante, mais non spécifié
- 【QT】對於Qt MSVC 2017無法編譯的問題解决
猜你喜欢

【QT】QtCreator卸载与安装(非正常状态)

2021 robocom world robot developer competition - semi finals of higher vocational group

下载在线视频 m3u8使用教程

深度学习 | 三个概念:Epoch, Batch, Iteration

Use pair to do unordered_ Key value of map
![Various global files related to [.Net core] program](/img/89/32623abf30d3dc92a3cdb1710a624f.png)
Various global files related to [.Net core] program

Windows installation WSL (II)

写给当前及未来博士研究生一些建议整理分享

LeetCode中等题题分享(5)

Graduation season is both a farewell and a new beginning
随机推荐
[QT] QT cannot find a solution to the compiler using msvc2017
PyTorch学习记录
Jielizhi, production line assembly link [chapter]
How excel opens CSV files with more than one million lines
Various global files related to [.Net core] program
Deep learning | three concepts: epoch, batch, iteration
Jielizhi Bluetooth headset quality control and production skills [chapter]
. env. XXX file, with constant, but undefined
The difference between timer and scheduledthreadpoolexecutor
Niuke - Practice 101 - reasoning clown
Windows10 install WSL (I) (wslregisterdistribution error)
.env.xxx 文件,加了常量,却undefined
Redis AOF log
ERP项目施行计划的目的是什么?
Overview of edge calculation
PostgreSQL notes (10) dynamically execute syntax parsing process
Timer和ScheduledThreadPoolExecutor的区别
[QT] solve the problem that QT MSVC 2017 cannot compile
【QT】Qt 使用MSVC2017找不到编译器的解决办法
cookie、session、tooken