当前位置:网站首页>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;
}
边栏推荐
- 2021 robocom world robot developer competition - preliminary competition of undergraduate group
- [leetcode] length of the last word [58]
- Why does blocprovider feel similar to provider?
- I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?
- 回顾数据脱敏系统
- Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
- Use pair to do unordered_ Key value of map
- Windows installation WSL (II)
- Is it safe to choose mobile phone for stock trading account opening in Beijing?
- [embedded system course design] a single key controls the LED light
猜你喜欢
Graduation season is both a farewell and a new beginning
2021 robocom world robot developer competition - preliminary competition of undergraduate group
LDR6035智能蓝牙音响可对手机设备持续充放电方案
第六章 数据流建模
BlocProvider为什么感觉和Provider很相似?
Digital transformation has a long way to go, so how to take the key first step
Material design component - use bottomsheet to show extended content (I)
[QT] qtcreator uninstall and installation (abnormal state)
Niuke - Practice 101 - reasoning clown
PostgreSQL source code (57) why is the performance gap so large in hot update?
随机推荐
Jielizhi Bluetooth headset quality control and production skills [chapter]
ConcurrentSkipListMap——跳表原理
Use vb Net to convert PNG pictures into icon type icon files
golang中的iota
USB-IF协会与各种接口的由来
牛客-练习赛101-推理小丑
Three methods of finding inverse numbers
使用htaccess文件禁止目录里的脚本执行权限
起床困难综合症(按位贪心)
ARP message header format and request flow
ADO. Net SqlDataAdapter object
Door level modeling - after class exercises
[untitled]
SecurityUtils. getSubject(). How to solve the problem that getprincipal() is null
ADO.NET之SqlDataAdpter对象
Shell process control
【ES实战】ES上的安全性运行方式
ADO.NET 之sqlConnection 对象使用摘要
PyCharm调用matplotlib绘图时图像弹出问题怎么解决
求逆序数的三个方法