当前位置:网站首页>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之B tree 以及 B+tree
- Material Design组件 - 使用BottomSheet展现扩展内容(一)
- Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
- 边缘计算概述
- Jielizhi, production line assembly link [chapter]
- Difficult to get up syndrome (bit by bit greed)
- SecurityUtils. getSubject(). How to solve the problem that getprincipal() is null
- ADO. Net SqlDataAdapter object
- ADO. Net SqlCommand object
- How to realize parallel replication in MySQL replication
猜你喜欢

Use pair to do unordered_ Key value of map

Relatively easy to understand PID understanding
![[must] bm41 output the right view of the binary tree [medium +]](/img/a5/00b2f0df5ab448665a2b062d145e52.png)
[must] bm41 output the right view of the binary tree [medium +]

Difficult to get up syndrome (bit by bit greed)

Windows10 install WSL (I) (wslregisterdistribution error)

Overview of edge calculation

Algolia's search needs are almost closed

Is there a piece of code that makes you convinced by human wisdom

关联性——组内相关系数

边缘计算概述
随机推荐
Operate database transactions with jpatractionmanager
vs2015 AdminDeployment.xml
Is it safe to buy funds on Great Wall Securities?
I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?
How excel opens CSV files with more than one million lines
USB-IF协会与各种接口的由来
Jielizhi Bluetooth headset quality control and production skills [chapter]
【QT】QtCreator卸载与安装(非正常状态)
在代码中使用SqlCommand对象
Concurrentskiplistmap -- principle of table skipping
ARP message header format and request flow
Applet form verification encapsulation
Using uni simple router, dynamically pass parameters typeerror: cannot convert undefined or null to object
使用 pair 做 unordered_map 的键值
Material Design组件 - 使用BottomSheet展现扩展内容(一)
启牛学院开户安全的吗?开户怎么开?
ADO. Net SqlConnection object usage summary
Three methods of finding inverse numbers
Kubernetes resource object introduction and common commands (III)
下载在线视频 m3u8使用教程