当前位置:网站首页>力扣: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];
}
};
边栏推荐
- See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
- The symbol table
- 7-1 LVS+NAT load balancing cluster, NAT mode deployment
- [C language advanced] program environment and preprocessing
- 2022软件测试面试题 最新字节跳动50道真题面试题 刷完已拿下15k 附讲解+答疑
- What are the functions of mall App development?
- 震惊,99.9% 的同学没有真正理解字符串的不可变性
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.3 什么是声明,什么是定义
- 【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
- 【流程图】
猜你喜欢
关于yolo7和gpu
【一步到位】Jenkins的安装、部署、启动(完整教程)
See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
符号表
[Cloud Native--Kubernetes] Pod Resource Management and Probe Detection
[Cocos 3.5.2]开启模型合批
OpenSSF 安全计划:SBOM 将驱动软件供应链安全
px、em、rem的区别
System design. Seckill system
结构体指针知识要点总结
随机推荐
Do you think border-radius is just rounded corners?【Various angles】
C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.5 Other Differences Between Arrays and Pointers
力扣题解8/3
备份工具pg_dump的使用《postgres》
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
Converts XML tags to TXT format (voc conversion for yolo convenient training)
商城App开发都有哪些功能呢
C Expert Programming Chapter 5 Thinking about Linking 5.1 Libraries, Linking and Loading
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
Landing, the IFC, GFC, FFC concept, layout rules, forming method, use is analysed
2022软件测试面试题 最新字节跳动50道真题面试题 刷完已拿下15k 附讲解+答疑
Hangdian Multi-School-Slipper- (tree map conversion + virtual point mapping)
3000字,一文带你搞懂机器学习!
2022 software test interview questions The latest ByteDance 50 real interview questions, 15k have been won after brushing, with explanation + Q&A
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
Jenkins export and import Job Pipeline
【云原生--Kubernetes】Pod资源管理与探针检测
C专家编程 第5章 对链接的思考 5.3 函数库链接的5个特殊秘密