当前位置:网站首页>leetcode96不同的二叉搜索树
leetcode96不同的二叉搜索树
2022-07-01 23:54: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;
}
边栏推荐
- Overview of edge calculation
- Regular expression collection
- SQL optimization
- Using uni simple router, dynamically pass parameters typeerror: cannot convert undefined or null to object
- 【.Net Core】程序相关各种全局文件
- Shell custom function
- 【QT】Qt 使用MSVC2017找不到编译器的解决办法
- Three methods of finding inverse numbers
- The best smart home open source system in 2022: introduction to Alexa, home assistant and homekit ecosystem
- 【CMake】Qt creator 里面的 cmake 配置
猜你喜欢
随机推荐
Deep learning | three concepts: epoch, batch, iteration
Using uni simple router, dynamically pass parameters typeerror: cannot convert undefined or null to object
The best smart home open source system in 2022: introduction to Alexa, home assistant and homekit ecosystem
mysql:insert ignore、insert和replace区别
vs2015 AdminDeployment. xml
PostgreSQL source code (57) why is the performance gap so large in hot update?
Windows 7 安装MYSQL 错误:1067
Li Kou today's question -241 Design priorities for operational expressions
【.Net Core】程序相关各种全局文件
2021 robocom world robot developer competition - preliminary competition of undergraduate group
openwrt 开启KV漫游
kubernetes资源对象介绍及常用命令(三)
SQL optimization
[QT] qtcreator uninstall and installation (abnormal state)
第六章 数据流建模
Redis master-slave synchronization
13 MySQL constraint
求逆序数的三个方法
How to display real-time 2D map after rviz is opened
Using SqlCommand objects in code









