当前位置:网站首页>力扣: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];
}
};
边栏推荐
- 杭电多校-Slipper-(树图转化+虚点建图)
- 使用Loadrunner进行性能测试
- 附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
- BFC、IFC、GFC、FFC概念理解、布局规则、形成方法、用处浅析
- Landing, the IFC, GFC, FFC concept, layout rules, forming method, use is analysed
- drools from download to postman request success
- 烧录场景下开发如何进行源代码保密工作
- 编程大杂烩(四)
- Teenage Achievement Hackers Need These Skills
- leetcode 12. 整数转罗马数字
猜你喜欢
结构体指针知识要点总结
信息学奥赛一本通 1312:【例3.4】昆虫繁殖
使用Loadrunner进行性能测试
心余力绌:企业面临的软件供应链安全困境
Typora 使用保姆级教程 | 看这一篇就够了 | 历史版本已被禁用
编程大杂烩(三)
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
There is an 8 hour difference between the docker installation of mysql and the host.
详解八大排序
随机推荐
C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
As soon as flink cdc is started, the CPU of the source Oracle server soars to more than 80%. What is the reason?
触觉智能分享-SSD20X实现升级显示进度条
【一步到位】Jenkins的安装、部署、启动(完整教程)
应届生软件测试薪资大概多少?
Mini program + e-commerce, fun new retail
高性能高可靠性高扩展性分布式防火墙架构
Programming hodgepodge (4)
Uni-app 小程序 App 的广告变现之路:全屏视频广告
Hangdian Multi-School-Slipper- (tree map conversion + virtual point mapping)
Converts XML tags to TXT format (voc conversion for yolo convenient training)
Chapter 5 C programming expert thinking 5.4 alert Interpositioning of links
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.3 What is a Declaration and What is a Definition
[C language advanced] program environment and preprocessing
某母婴小程序加密参数解密
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
drools from download to postman request success