当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

.env.xxx 文件,加了常量,卻undefined

使用VB.net将PNG图片转成icon类型图标文件

Notblank and notempty

Use vb Net to convert PNG pictures into icon type icon files

深度学习 | 三个概念:Epoch, Batch, Iteration
![Various global files related to [.Net core] program](/img/89/32623abf30d3dc92a3cdb1710a624f.png)
Various global files related to [.Net core] program

UDS bootloader of s32kxxx bootloader

LDR6035智能蓝牙音响可对手机设备持续充放电方案

Asp .NetCore 微信订阅号自动回复之文本篇
![Jielizhi, production line assembly link [chapter]](/img/1d/d1736fad33c428e61f450aad512ce0.png)
Jielizhi, production line assembly link [chapter]
随机推荐
Write some suggestions to current and future doctoral students to sort out and share
时间复杂度与空间复杂度
ADO. Net SqlConnection object usage summary
2021 robocom world robot developer competition - preliminary competition of higher vocational group
【CMake】Qt creator 里面的 cmake 配置
ADO. Net SqlDataAdapter object
LDR6035智能蓝牙音响可充可放(5.9.12.15.20V)快充快放设备充电
Which securities company is the best to open a stock account? Is there a security guarantee
学成在线案例实战
Regular expression collection
下载在线视频 m3u8使用教程
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决
Algolia's search needs are almost closed
cookie、session、tooken
Similarities and differences between the defined identity execution function authid determiner and PostgreSQL in Oracle
ARP message header format and request flow
Material Design组件 - 使用BottomSheet展现扩展内容(一)
ADO.NET 之sqlConnection 对象使用摘要
牛客-练习赛101-推理小丑
[untitled]