当前位置:网站首页>力扣:96.不同的二叉搜索树
力扣:96.不同的二叉搜索树
2022-08-04 05:14:00 【empty__barrel】
题目:
给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。
思路:
dp[n]含义:n个节点构成的二叉搜索树的种类数。
n个节点构成的二叉搜索树的种类数,可以分类为头结点为1一直到头结点为n,这n种二叉搜索树。二叉搜索树头结点的左子树的节点值都小于头结点,二叉搜索树头结点的右子树的节点值都大于头结点。例如:若计算头结点值为3这类树的种类数, 那么头结点左子树的节点数为2个,头结点右子树的节点数为n-3个。此时左子树有dp[2]种,此时右子树有dp[n-3]种。那么头结点为3这类树的种类数为dp[ 2 ] * dp[ n-3 ]。此时头结点的值可能性为1到n,通过这种方法将以头结点不同来区分的每一个种类的二叉搜索树的种类数相加即可。
所以递推公式:dp[i] += dp[j - 1] * dp[i - j]; ,j-1 为j为头结点左子树节点数量,i-j 为以j为头结点右子树节点数量
代码:
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1);
dp[0] = 1;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= i; ++j){
dp[i] += dp[j-1]*dp[i-j];
}
}
return dp[n];
}
};
边栏推荐
猜你喜欢
转:管理是对可能性的热爱,管理者要有闯进未知的勇气
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
获取单选框选中内容
About yolo7 and gpu
mysql index notes
How to simplify the automation of modern e-procurement?
高性能高可靠性高扩展性分布式防火墙架构
【21天学习挑战赛】图像的旋转问题(二维数组)
【评价类模型】Topsis法(优劣解距离法)
解决错误:npm WARN config global `--global`, `--local` are deprecated
随机推荐
解决错误:npm WARN config global `--global`, `--local` are deprecated
少年成就黑客,需要这些技能
某母婴小程序加密参数解密
[Cocos 3.5.2]开启模型合批
[SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test
8. Haproxy builds a web cluster
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
go module的介绍与应用
The 2022 PMP exam has been delayed, should we be happy or worried?
使用Loadrunner进行性能测试
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
【流程图】
C专家编程 第5章 对链接的思考 5.3 函数库链接的5个特殊秘密
深度学习环境配置
Converts XML tags to TXT format (voc conversion for yolo convenient training)
C专家编程 第5章 对链接的思考 5.6 轻松一下---看看谁在说话:挑战Turning测验
7-2 LVS+DR Overview and Deployment
[Skill] Using Sentinel to achieve priority processing of requests
leetcode 12. Integer to Roman numeral
C Expert Programming Chapter 5 Thinking about Linking 5.2 Advantages of Dynamic Linking