保研随笔录
上一届的夏令营已经陆续结束。一年后的我,又会是怎样的状态?是拿到心仪的 offer,还是全然失败、准备九推?
与其焦虑地等待,不如从头开始提升自我。我将记录这一路的辛酸苦辣,尽管结果未必如意。
起点
从大二下学期期末开始,心里总是隐约不安。大一的全盘失败让我进退两难:科研没有什么成果,绩点甚至没上 90,只能排在专业 50%。在德育分和智育分都不太理想的情况下,我必须在保证绩点的同时做出科研成果。
大二的每一门课程都不是善茬,我的容错太低了,尽管知道很多内容一辈子也不会用上,但我必须强迫自己把这些内容缓存进自己有限的脑容量中。
这已经是我能做到的最大努力,有些老师不当人确实没办法
靓如姐保到了浙软,泽中保到了北大。熟悉的人奔向了不同的去向,我能否和他们一样有一个好的归宿?和他们相比,我欠缺了什么?还有哪些地方可以补足,又有哪些教训值得吸取?我必须认清自己。
不足与应对
| # | 不足 | 应对方案 |
|---|---|---|
| 1 | 代码能力薄弱:看得懂、有概念,但实操能力较差。平时过度依赖 AI 写代码,学院培养方案也不重视实践 | 9 月前学完基础知识;接下来的半年多坚持每天刷算法题,掌握套路与模板。一方面参加校内程序设计大赛、蓝桥杯等比赛,争取德育分;另一方面为夏令营和预推免机试做准备 |
| 2 | 项目经历几乎为 0,缺乏工程实践训练和实习经历 | 大三上学期末开始校外实习,最好是线下实习;注意维护人际关系,在 GitHub、牛客上多了解他人的实习经历 |
| 3 | 无法应对突发情况,比如申请港科,托福还没着落 | 提前准备好各种材料,尽早决定是否考雅思/托福、是否参加数竞、是否参加大英赛 |
| 4 | 课内成绩可能无法达到目标院校的门槛 | 在保证科研和其他学习任务进度的同时,尽可能提高课内成绩,同时把握好德育分 |
| 5 | 科研成果挂零 | 8 月整理思路、重新确定方向,全面推进科研进度 |
关键节点(时间线)
| 时间 | 节点 | 状态 |
|---|---|---|
| 2026.08 | 整理思路,重新确定方向,全面启动科研 | ⬜ 待办 |
| 2026.09 | 学完基础知识 | ✅ 已于 2026-08-04 完成 |
| 2026.09—2027.05 | 每天刷算法题(备战蓝桥杯、校内程序设计大赛) | ⬜ 待办 |
| 2027.01 | 大三上学期末,开始校外实习 | ⬜ 待办 |
| 2027.07 | 夏令营 | ⬜ 待办 |
| 2027.09 | 预推免 / 九推 | ⬜ 待办 |
知识索引
- 资源与规划
- 复杂度与计算机基础
- 数组
- 链表
- 哈希表
- 字符串
- 栈与队列
- 二叉树
- 基础:二叉树理论基础
- 递归遍历:二叉树的递归遍历
- 迭代遍历:二叉树的迭代遍历
- 深度:二叉树的最大深度、二叉树的最小深度
- 节点统计:完全二叉树的节点个数
- 平衡判断:平衡二叉树
- 路径与回溯:二叉树的所有路径
- 叶子节点:左叶子之和
- 层序定位:找树左下角的值
- 路径判断:路径总和
- 树的构造:从中序与后序遍历序列构造二叉树
- 递归构造:最大二叉树、合并二叉树
- 搜索:二叉搜索树中的搜索
- 合法性:验证二叉搜索树
- 相邻差值:二叉搜索树的最小绝对差
- 频率统计:二叉搜索树中的众数
- 最近公共祖先:二叉树、二叉搜索树
- 插入:二叉搜索树中的插入操作
- 删除与修剪:删除二叉搜索树中的节点、修剪二叉搜索树
- 平衡构造:将有序数组转换为二叉搜索树
- 累加树:把二叉搜索树转换为累加树
- 总结:二叉树总结
- 回溯算法
- Git
- 贪心算法
- 动态规划
- 基础:动态规划理论基础
- 基础递推:斐波那契数
- 爬楼梯:爬楼梯、使用最小花费爬楼梯、爬楼梯(进阶版)
- 网格路径:不同路径、不同路径 II
- 整数拆分:整数拆分
- 树形计数:不同的二叉搜索树
- 0-1 背包:背包理论基础(二维)、背包理论基础(滚动数组)
- 子集背包:分割等和子集
- 分组背包:最后一块石头的重量 II
- 计数背包:目标和
- 多维背包:一和零
- 完全背包:完全背包理论基础
- 完全背包计数:零钱兑换 II、组合总和 IV
- 完全背包最小值:零钱兑换、完全平方数
- 字符串拆分:单词拆分
- 多重背包:多重背包理论基础
- 打家劫舍:线性房屋、环形房屋、树形房屋
- 股票交易:单次交易、多次交易、最多两笔交易、含手续费
- 递增序列:最长递增子序列、最长连续递增序列
- 公共序列:最长重复子数组、最长公共子序列、不相交的线
- 连续子数组:最大子序和
- 子序列匹配:判断子序列、不同的子序列
- 字符串编辑:两个字符串的删除操作、编辑距离
- 回文问题:回文子串、最长回文子序列
- 总结:动态规划总结
- 单调栈
- 图论
- 基础:图论理论基础
- 路径枚举:所有可达路径
- 图搜索:广度优先搜索理论基础
- 连通块:岛屿数量
- 岛屿面积:岛屿的最大面积、孤岛的总面积
- 逆向搜索:水流问题
- 连通块合并:建造最大岛屿
- 边界计数:岛屿的周长
- 无权最短路:字符串接龙
- 单源可达性:有向图的完全联通
- 并查集:并查集理论基础
- 无向连通性:寻找存在的路径
- 无向图判环:冗余连接
- 有向树修复:冗余连接 II
- 最小生成树:Prim 算法
- 边排序生成树:Kruskal 算法
- 依赖排序:拓扑排序
- 非负权最短路:Dijkstra(朴素版)、Dijkstra(堆优化版)
学习历程(持续更新)
2026-07-31(周五)
- 搜集算法学习与刷题网站:代码随想录、LeetCode 热题 100
- 信息与经验渠道:牛客(实习、面经、保研经验等)
2026-08-01(周六)
时间复杂度
- 理解大 O 表示法
- 了解不同数据规模对算法复杂度的要求
- 掌握复杂表达式的化简方法
- 理解
O(log n)中对数底数的影响 - 练习分析时间复杂度:从 个字符串中找出相同的两个字符串(假设仅有两个字符串相同)
程序为什么会超时
- 从硬件配置出发,大致了解 CPU 的执行速度
- 万赫兹
- 任何开发计算机程序的软件工程师都应该能够估计,这个程序的运行时间是一秒钟还是一年。
2026-08-04(周二)
空间复杂度
- 空间复杂度分析
- 递归算法的时间与空间复杂度分析:
- 斐波那契数列:对比
fibonacci(i - 1) + fibonacci(i - 2)与fibonacci(second, first + second, n - 1)两种递归写法 - 二分法(递归实现)的性能分析
- 递归算法的空间复杂度 ≈ 单层调用所需空间 × 最大递归深度
- 递归算法的时间复杂度 ≈ 递归调用总次数 × 单次调用的非递归工作量
- 斐波那契数列:对比
代码的内存消耗
- 固定部分:代码区、数据区
- 可变部分:栈区(自动分配与回收)、堆区(可通过
new动态分配,使用完成后应正确释放) - 内存泄漏:动态分配的内存在不再使用后未被释放
- 指针大小与寻址范围:
- 典型 32 位平台:指针大小为 4 Byte,理论寻址空间为 Byte,即 4 GB
- 典型 64 位平台:指针大小为 8 Byte,理论寻址空间为 Byte,实际可用范围受硬件和操作系统限制
- 内存对齐:
- 平台原因:并非所有硬件平台都能访问任意内存地址上的任意数据。某些平台只能在特定地址处读取特定类型的数据,否则会抛出硬件异常。为了让同一程序能够在多个平台上运行,需要进行内存对齐。
- 硬件原因:经过内存对齐后,CPU 访问内存的速度会显著提升。
- 阶段进度:基础知识学习至此结束。
2026-08-08(周六)
最近总是偷懒 😠,要克服这种心理。
数组(一)
一、数组理论
- 数组是存放在连续内存空间上的相同类型数据的集合。
- C++ 中的二维数组在地址空间上是连续的。
int array[2][3] = {
{0, 1, 2},
{3, 4, 5}
};int array[2][3] = {
{0, 1, 2},
{3, 4, 5}
};数组地址:
0x7ffee4065820 0x7ffee4065824 0x7ffee4065828
0x7ffee406582c 0x7ffee4065830 0x7ffee40658340x7ffee4065820 0x7ffee4065824 0x7ffee4065828
0x7ffee406582c 0x7ffee4065830 0x7ffee4065834二、二分查找
区间通常有两种定义:左闭右闭 [left, right],或左闭右开 [left, right)。
- 版本一:左闭右闭
[left, right]
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
// target 位于左闭右闭区间 [left, right]
int right = nums.size() - 1;
// 当 left == right 时,[left, right] 仍然有效,因此使用 <=
while (left <= right) {
// 防止溢出,等同于 (left + right) / 2
int middle = left + ((right - left) / 2);
if (nums[middle] > target) {
// target 位于左区间 [left, middle - 1]
right = middle - 1;
} else if (nums[middle] < target) {
// target 位于右区间 [middle + 1, right]
left = middle + 1;
} else {
// 找到目标值,返回下标
return middle;
}
}
// 未找到目标值
return -1;
}
};class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
// target 位于左闭右闭区间 [left, right]
int right = nums.size() - 1;
// 当 left == right 时,[left, right] 仍然有效,因此使用 <=
while (left <= right) {
// 防止溢出,等同于 (left + right) / 2
int middle = left + ((right - left) / 2);
if (nums[middle] > target) {
// target 位于左区间 [left, middle - 1]
right = middle - 1;
} else if (nums[middle] < target) {
// target 位于右区间 [middle + 1, right]
left = middle + 1;
} else {
// 找到目标值,返回下标
return middle;
}
}
// 未找到目标值
return -1;
}
};- 版本二:左闭右开
[left, right)
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
// target 位于左闭右开区间 [left, right)
int right = nums.size();
// 当 left == right 时,[left, right) 无效,因此使用 <
while (left < right) {
int middle = left + ((right - left) >> 1);
if (nums[middle] > target) {
// target 位于左区间 [left, middle)
right = middle;
} else if (nums[middle] < target) {
// target 位于右区间 [middle + 1, right)
left = middle + 1;
} else {
// 找到目标值,返回下标
return middle;
}
}
// 未找到目标值
return -1;
}
};class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
// target 位于左闭右开区间 [left, right)
int right = nums.size();
// 当 left == right 时,[left, right) 无效,因此使用 <
while (left < right) {
int middle = left + ((right - left) >> 1);
if (nums[middle] > target) {
// target 位于左区间 [left, middle)
right = middle;
} else if (nums[middle] < target) {
// target 位于右区间 [middle + 1, right)
left = middle + 1;
} else {
// 找到目标值,返回下标
return middle;
}
}
// 未找到目标值
return -1;
}
};2026-08-10(周一)
数组(二)
三、移除元素
- 题目:27. 移除元素
- 暴力解法:使用两层
for循环。第一层遍历数组元素;发现需要移除的元素后,第二层将后续元素整体向前移动一位。- 时间复杂度:
- 空间复杂度:
- 双指针法(快慢指针法):通过快、慢指针,在一层
for循环中完成两层循环的工作。- 快指针:寻找新数组的元素,即不等于目标值的元素
- 慢指针:指向新数组中待更新的下标
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};四、有序数组的平方
- 题目:977. 有序数组的平方
- 暴力排序:将每个数平方后排序,时间复杂度为 。
- 双指针法:原数组有序,平方后的最大值只可能出现在数组两端。新建与原数组等长的
result,令k指向其末尾:- 若
A[i] * A[i] < A[j] * A[j],则执行result[k--] = A[j] * A[j] - 否则,执行
result[k--] = A[i] * A[i] - 时间复杂度:
- 空间复杂度:
- 若
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int k = A.size() - 1;
vector<int> result(A.size(), 0);
// 最后仍需处理 i == j 时的元素,因此使用 <=
for (int i = 0, j = A.size() - 1; i <= j;) {
if (A[i] * A[i] < A[j] * A[j]) {
result[k--] = A[j] * A[j];
j--;
} else {
result[k--] = A[i] * A[i];
i++;
}
}
return result;
}
};class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int k = A.size() - 1;
vector<int> result(A.size(), 0);
// 最后仍需处理 i == j 时的元素,因此使用 <=
for (int i = 0, j = A.size() - 1; i <= j;) {
if (A[i] * A[i] < A[j] * A[j]) {
result[k--] = A[j] * A[j];
j--;
} else {
result[k--] = A[i] * A[i];
i++;
}
}
return result;
}
};五、长度最小的子数组
- 题目:209. 长度最小的子数组
- 暴力解法:使用两层
for循环,不断寻找符合条件的子数组,时间复杂度为 。 - 滑动窗口:不断调整子数组的起始位置和终止位置,从而得到满足条件的最短子数组。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int result = INT32_MAX;
int sum = 0; // 滑动窗口内元素之和
int i = 0; // 滑动窗口起始位置
int subLength = 0; // 滑动窗口长度
for (int j = 0; j < nums.size(); j++) {
sum += nums[j];
// 使用 while 持续更新起始位置,并判断子数组是否符合条件
while (sum >= s) {
subLength = j - i + 1;
result = result < subLength ? result : subLength;
// 不断变更 i,缩小滑动窗口
sum -= nums[i++];
}
}
// result 未被更新,说明没有符合条件的子数组
return result == INT32_MAX ? 0 : result;
}
};class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int result = INT32_MAX;
int sum = 0; // 滑动窗口内元素之和
int i = 0; // 滑动窗口起始位置
int subLength = 0; // 滑动窗口长度
for (int j = 0; j < nums.size(); j++) {
sum += nums[j];
// 使用 while 持续更新起始位置,并判断子数组是否符合条件
while (sum >= s) {
subLength = j - i + 1;
result = result < subLength ? result : subLength;
// 不断变更 i,缩小滑动窗口
sum -= nums[i++];
}
}
// result 未被更新,说明没有符合条件的子数组
return result == INT32_MAX ? 0 : result;
}
};六、螺旋矩阵 II
- 题目:59. 螺旋矩阵 II
- 核心原则:坚持循环不变量,四条边均采用左闭右开的处理方式。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0, starty = 0; // 每一圈的起始位置
int loop = n / 2; // 需要循环的圈数
int mid = n / 2; // 矩阵中心位置
int count = 1; // 当前待填入的数值
int offset = 1; // 控制每条边遍历的长度
int i, j;
while (loop--) {
i = startx;
j = starty;
// 上边:从左到右(左闭右开)
for (; j < n - offset; j++) {
res[i][j] = count++;
}
// 右边:从上到下(左闭右开)
for (; i < n - offset; i++) {
res[i][j] = count++;
}
// 下边:从右到左(左闭右开)
for (; j > starty; j--) {
res[i][j] = count++;
}
// 左边:从下到上(左闭右开)
for (; i > startx; i--) {
res[i][j] = count++;
}
startx++;
starty++;
offset++;
}
// n 为奇数时,单独为矩阵中心赋值
if (n % 2) {
res[mid][mid] = count;
}
return res;
}
};class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0, starty = 0; // 每一圈的起始位置
int loop = n / 2; // 需要循环的圈数
int mid = n / 2; // 矩阵中心位置
int count = 1; // 当前待填入的数值
int offset = 1; // 控制每条边遍历的长度
int i, j;
while (loop--) {
i = startx;
j = starty;
// 上边:从左到右(左闭右开)
for (; j < n - offset; j++) {
res[i][j] = count++;
}
// 右边:从上到下(左闭右开)
for (; i < n - offset; i++) {
res[i][j] = count++;
}
// 下边:从右到左(左闭右开)
for (; j > starty; j--) {
res[i][j] = count++;
}
// 左边:从下到上(左闭右开)
for (; i > startx; i--) {
res[i][j] = count++;
}
startx++;
starty++;
offset++;
}
// n 为奇数时,单独为矩阵中心赋值
if (n % 2) {
res[mid][mid] = count;
}
return res;
}
};2026-08-11(周二)
数组(三)
七、区间和
- 题目:58. 区间和(第九期模拟笔试)
- 暴力解法:对于每个查询区间,重新遍历并累加区间内的所有元素。
- 前缀和:适用于需要频繁计算区间和的问题。
p[i]表示数组vec中下标0到i的元素之和- 当
a == 0时,区间和为p[b] - 当
a > 0时,区间和为p[b] - p[a - 1] - 预处理时间复杂度:
- 单次查询时间复杂度:
- 空间复杂度:
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n, a, b;
scanf("%d", &n);
vector<int> vec(n);
vector<int> prefix(n);
int prefixSum = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &vec[i]);
prefixSum += vec[i];
prefix[i] = prefixSum;
}
while (scanf("%d%d", &a, &b) == 2) {
int sum = (a == 0) ? prefix[b] : prefix[b] - prefix[a - 1];
printf("%d\n", sum);
}
return 0;
}#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n, a, b;
scanf("%d", &n);
vector<int> vec(n);
vector<int> prefix(n);
int prefixSum = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &vec[i]);
prefixSum += vec[i];
prefix[i] = prefixSum;
}
while (scanf("%d%d", &a, &b) == 2) {
int sum = (a == 0) ? prefix[b] : prefix[b] - prefix[a - 1];
printf("%d\n", sum);
}
return 0;
}面对大量数据的输入与输出时,使用
scanf和printf通常比默认的cin和cout耗时更少。
八、开发商购买土地
- 题目:44. 开发商购买土地(第五期模拟笔试)
- 暴力解法:使用一层
for循环枚举分割线,再用两层for循环分别累加分割线两侧的土地价值。 - 前缀和思路:
- 统计矩阵的总价值。
- 分别计算每行与每列的价值之和。
- 累加分割线一侧的价值,并用
abs(sum - 2 * cut)计算两侧价值之差。 - 分别枚举横向和纵向分割线,取最小差值。
- 时间复杂度:
- 空间复杂度:
#include <algorithm>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<vector<int>> vec(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> vec[i][j];
sum += vec[i][j];
}
}
// 统计每行的价值之和
vector<int> horizontal(n, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
horizontal[i] += vec[i][j];
}
}
// 统计每列的价值之和
vector<int> vertical(m, 0);
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
vertical[j] += vec[i][j];
}
}
int result = INT_MAX;
int horizontalCut = 0;
// 分割线必须位于两行之间,因此不枚举最后一行之后的位置
for (int i = 0; i < n - 1; i++) {
horizontalCut += horizontal[i];
result = min(result, abs(sum - 2 * horizontalCut));
}
int verticalCut = 0;
// 分割线必须位于两列之间
for (int j = 0; j < m - 1; j++) {
verticalCut += vertical[j];
result = min(result, abs(sum - 2 * verticalCut));
}
cout << result << endl;
return 0;
}#include <algorithm>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<vector<int>> vec(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> vec[i][j];
sum += vec[i][j];
}
}
// 统计每行的价值之和
vector<int> horizontal(n, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
horizontal[i] += vec[i][j];
}
}
// 统计每列的价值之和
vector<int> vertical(m, 0);
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
vertical[j] += vec[i][j];
}
}
int result = INT_MAX;
int horizontalCut = 0;
// 分割线必须位于两行之间,因此不枚举最后一行之后的位置
for (int i = 0; i < n - 1; i++) {
horizontalCut += horizontal[i];
result = min(result, abs(sum - 2 * horizontalCut));
}
int verticalCut = 0;
// 分割线必须位于两列之间
for (int j = 0; j < m - 1; j++) {
verticalCut += vertical[j];
result = min(result, abs(sum - 2 * verticalCut));
}
cout << result << endl;
return 0;
}九、数组总结
核心特性
- 数组是存放在连续内存空间上的相同类型数据的集合。
- 数组下标从 0 开始。
- 数组元素的内存地址连续,因此删除或添加元素时,通常需要移动其他元素。
经典方法
- 二分查找:坚持循环不变量,统一维护区间定义。
- 双指针:通过快、慢指针在一层
for循环中完成两层循环的工作。 - 滑动窗口:根据当前子数组的状态不断调整起始位置,将部分 的暴力解法优化至 。
- 模拟:坚持循环不变量,统一每一轮的处理规则。
- 前缀和:预处理累计和,使用
prefix[b] - prefix[a - 1]快速计算区间和。
知识图谱
2026-08-12(周三)
链表(一)
一、链表理论基础
定义
链表是一种通过指针串联起来的线性结构。每个节点由两部分组成:
- 数据域:存储节点中的数据
- 指针域:存储指向下一个节点的指针;最后一个节点的指针域指向
nullptr
常见类型
- 单链表:每个节点的指针域只能指向下一个节点
- 双链表:每个节点有两个指针域,分别指向前一个节点和后一个节点
- 循环链表:链表首尾相连,尾节点指向头节点
存储方式
数组元素在内存中连续分布,而链表节点通常不连续分布。链表通过节点指针,将分散在内存中的节点连接起来。
// 单链表节点
struct ListNode {
int val; // 节点中存储的元素
ListNode* next; // 指向下一个节点
ListNode(int x) : val(x), next(nullptr) {}
};// 单链表节点
struct ListNode {
int val; // 节点中存储的元素
ListNode* next; // 指向下一个节点
ListNode(int x) : val(x), next(nullptr) {}
};如果没有定义接受参数的构造函数,就不能使用
ListNode node(x)这种方式直接为节点值初始化。
基本操作
- 删除节点 D:将节点 C 的
next指向节点 E,再手动释放节点 D - 在 C 与 D 之间添加节点 F:先将 F 的
next指向 D,再将 C 的next指向 F
数组与链表的性能对比
| 数据结构 | 插入 / 删除 | 按下标查询 | 长度与适用场景 |
|---|---|---|---|
| 数组 | 长度通常预先确定,适合频繁查询 | ||
| 链表 | 已知目标位置时为 | 长度可动态变化,适合频繁增删、较少查询 |
二、移除链表元素
- 题目:203. 移除链表元素
- 直接操作原链表:头节点没有前驱节点,因此需要分别处理头节点和非头节点。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 连续删除值等于 val 的头节点,注意这里使用 while 而非 if
while (head != nullptr && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// 删除非头节点
ListNode* cur = head;
while (cur != nullptr && cur->next != nullptr) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 连续删除值等于 val 的头节点,注意这里使用 while 而非 if
while (head != nullptr && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// 删除非头节点
ListNode* cur = head;
while (cur != nullptr && cur->next != nullptr) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};虚拟头节点
设置虚拟头节点后,原头节点和其他节点可以使用同一套删除逻辑,避免单独处理头节点。
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;三、设计链表
- 题目:707. 设计链表
- 核心设计:使用虚拟头节点统一链表的插入与删除操作,并用
_size记录有效节点数量。
class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val) : val(val), next(nullptr) {}
};
MyLinkedList() {
_dummyHead = new LinkedNode(0);
_size = 0;
}
~MyLinkedList() {
while (_dummyHead != nullptr) {
LinkedNode* tmp = _dummyHead;
_dummyHead = _dummyHead->next;
delete tmp;
}
}
int get(int index) {
if (index < 0 || index >= _size) {
return -1;
}
LinkedNode* cur = _dummyHead->next;
while (index--) {
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedNode* newNode = new LinkedNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
_size++;
}
void addAtTail(int val) {
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) {
return;
}
if (index < 0) {
index = 0;
}
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
_size++;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= _size) {
return;
}
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
LinkedNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
_size--;
}
private:
LinkedNode* _dummyHead;
int _size;
};class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val) : val(val), next(nullptr) {}
};
MyLinkedList() {
_dummyHead = new LinkedNode(0);
_size = 0;
}
~MyLinkedList() {
while (_dummyHead != nullptr) {
LinkedNode* tmp = _dummyHead;
_dummyHead = _dummyHead->next;
delete tmp;
}
}
int get(int index) {
if (index < 0 || index >= _size) {
return -1;
}
LinkedNode* cur = _dummyHead->next;
while (index--) {
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedNode* newNode = new LinkedNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
_size++;
}
void addAtTail(int val) {
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) {
return;
}
if (index < 0) {
index = 0;
}
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
_size++;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= _size) {
return;
}
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
LinkedNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
_size--;
}
private:
LinkedNode* _dummyHead;
int _size;
};2026-08-13(周四)
链表(二)
四、反转链表
- 题目:206. 反转链表
- 双指针法:使用
cur遍历原链表,使用pre指向已完成反转的部分。改变cur->next前,必须先用temp保存下一个节点。 - 时间复杂度:
- 空间复杂度:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur != nullptr) {
// 保存下一个节点,避免改变 cur->next 后丢失后续链表
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur != nullptr) {
// 保存下一个节点,避免改变 cur->next 后丢失后续链表
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};五、删除链表的倒数第 N 个节点
- 题目:19. 删除链表的倒数第 N 个节点
- 快慢指针法:
- 创建虚拟头节点,使删除头节点与删除其他节点使用同一套逻辑。
fast先从虚拟头节点出发移动 步,使fast与slow之间保持 步的间隔。- 同时移动两个指针,直到
fast指向nullptr;此时slow恰好指向待删除节点的前一个节点。 - 调整指针并释放待删除节点。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
// 让 slow 最终停在待删除节点的前一个节点
for (int i = 0; i <= n; i++) {
fast = fast->next;
}
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode* tmp = slow->next;
slow->next = tmp->next;
delete tmp;
ListNode* newHead = dummyHead->next;
delete dummyHead;
return newHead;
}
};class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
// 让 slow 最终停在待删除节点的前一个节点
for (int i = 0; i <= n; i++) {
fast = fast->next;
}
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode* tmp = slow->next;
slow->next = tmp->next;
delete tmp;
ListNode* newHead = dummyHead->next;
delete dummyHead;
return newHead;
}
};七、链表相交
- 题目:面试题 02.07. 链表相交
- 长度对齐法:
- 分别计算链表 A 与链表 B 的长度。
- 让较长链表的指针先移动长度差,使两个指针到链表末尾的距离相同。
- 同时向后移动两个指针;首次指向同一节点时,该节点就是相交节点。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0;
int lenB = 0;
while (curA != nullptr) {
lenA++;
curA = curA->next;
}
while (curB != nullptr) {
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 保证 curA 指向较长链表,lenA 为较大长度
if (lenB > lenA) {
swap(lenA, lenB);
swap(curA, curB);
}
// 将两个链表按末尾对齐
int gap = lenA - lenB;
while (gap--) {
curA = curA->next;
}
while (curA != nullptr) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0;
int lenB = 0;
while (curA != nullptr) {
lenA++;
curA = curA->next;
}
while (curB != nullptr) {
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 保证 curA 指向较长链表,lenA 为较大长度
if (lenB > lenA) {
swap(lenA, lenB);
swap(curA, curB);
}
// 将两个链表按末尾对齐
int gap = lenA - lenB;
while (gap--) {
curA = curA->next;
}
while (curA != nullptr) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};2026-08-14(周五)
链表(三)
八、环形链表 II
- 题目:142. 环形链表 II
- 需要解决两个问题:
- 判断链表中是否存在环。
- 如果存在环,找到环的入口节点。
判断是否存在环
使用快慢指针:fast 每次移动两个节点,slow 每次移动一个节点。如果两个指针在途中相遇,说明链表中存在环;如果 fast 或 fast->next 指向 nullptr,说明链表中不存在环。
寻找环的入口
假设:
- 从头节点到环入口的距离为
- 从环入口到快慢指针相遇点的距离为
- 从相遇点回到环入口的距离为
fast在环内绕了 圈
相遇时,slow 与 fast 经过的距离分别为:
由于 fast 的速度是 slow 的两倍:
整理可得:
因此,分别从头节点与快慢指针相遇点出发两个指针,并让它们每次各移动一个节点;二者再次相遇的位置就是环的入口。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
ListNode* detectCycle(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,说明链表中存在环
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
// 从相遇点和头节点同时出发,再次相遇处就是环入口
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return nullptr;
}
};class Solution {
public:
ListNode* detectCycle(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,说明链表中存在环
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
// 从相遇点和头节点同时出发,再次相遇处就是环入口
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return nullptr;
}
};九、链表总结
理论基础
- 常见类型:单链表、双链表、循环链表
- 存储方式:节点通常分散在内存中,通过指针连接
- 基本操作:链表的增加、删除、修改与查询
- 性能分析:理解数组和链表在不同使用场景中的优劣
经典方法与题目
- 虚拟头节点:统一头节点与其他节点的处理逻辑,避免单独分类讨论
- 链表基本操作:设计链表
- 迭代双指针:反转链表
- 快慢指针与虚拟头节点:删除链表的倒数第 N 个节点
- 长度对齐:链表相交
- 快慢指针:判断链表是否有环并寻找环入口
2026-08-15(周六)
哈希表(一)
哈希表用于快速判断元素是否出现、统计元素频率以及建立键值映射,是数组与字符串题目中的高频工具。
一、哈希表理论基础
基本概念
- 哈希表:根据关键码的值直接访问数据的数据结构。
- 哈希函数:通过
hashCode将键转换为数值,再映射到哈希表的索引位置。 - 哈希碰撞:不同的键经过哈希函数计算后,被映射到同一个索引位置。
哈希碰撞的解决方法
- 拉链法:将发生冲突的元素存储在同一个链表中。需要选择合适的表大小,避免空槽过多浪费内存,也避免链表过长降低查询效率。
- 线性探测法:依靠哈希表中的空槽解决冲突。发生碰撞时,按顺序继续寻找下一个空槽;因此需要保证
tableSize > dataSize。
常用哈希结构
- 数组
set(集合)map(映射)
C++ 集合容器对比
| 容器 | 底层实现 | 是否有序 | 元素能否重复 | 元素能否直接修改 | 查询效率 | 增删效率 |
|---|---|---|---|---|---|---|
std::set | 红黑树 | 有序 | 否 | 否 | ||
std::multiset | 红黑树 | 有序 | 是 | 否 | ||
std::unordered_set | 哈希表 | 无序 | 否 | 否 | 平均 | 平均 |
C++ 映射容器对比
| 容器 | 底层实现 | 键是否有序 | 键能否重复 | 键能否修改 | 映射值能否修改 | 查询效率 | 增删效率 |
|---|---|---|---|---|---|---|---|
std::map | 红黑树 | 有序 | 否 | 否 | 是 | ||
std::multimap | 红黑树 | 有序 | 是 | 否 | 是 | ||
std::unordered_map | 哈希表 | 无序 | 否 | 否 | 是 | 平均 | 平均 |
红黑树是一种平衡二叉搜索树。为了维持内部顺序,
set中的元素以及map中的键不能直接修改;需要先删除,再插入新值。
二、有效的字母异位词
- 题目:242. 有效的字母异位词
- 暴力解法:使用两层
for循环逐一匹配字符,时间复杂度为 。 - 数组哈希:题目限定字符为小写英文字母,因此可以使用长度为 26 的
record数组记录各字母出现的次数。- 遍历字符串
s,对record[s[i] - 'a']执行加一操作。 - 遍历字符串
t,对record[t[i] - 'a']执行减一操作。 - 如果最终所有元素均为 0,则两个字符串互为字母异位词。
- 遍历字符串
- 时间复杂度:
- 空间复杂度:,因为数组长度固定为 26
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {0};
for (char ch : s) {
// 只需计算字符相对 'a' 的偏移量
record[ch - 'a']++;
}
for (char ch : t) {
record[ch - 'a']--;
}
for (int count : record) {
if (count != 0) {
return false;
}
}
return true;
}
};class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {0};
for (char ch : s) {
// 只需计算字符相对 'a' 的偏移量
record[ch - 'a']++;
}
for (char ch : t) {
record[ch - 'a']--;
}
for (int count : record) {
if (count != 0) {
return false;
}
}
return true;
}
};三、两个数组的交集
- 题目:349. 两个数组的交集
- 选择哈希结构:当数值范围较小时,可以使用数组作为哈希表;当数值范围不固定时,使用
unordered_set更合适。 - 解题思路:
- 使用
numsSet保存nums1中出现过的元素。 - 遍历
nums2,将同时出现在numsSet中的元素加入resultSet。 - 使用集合自动去重,最后转换为
vector返回。
- 使用
- 平均时间复杂度:
- 空间复杂度:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> numsSet(nums1.begin(), nums1.end());
unordered_set<int> resultSet;
for (int num : nums2) {
if (numsSet.find(num) != numsSet.end()) {
resultSet.insert(num);
}
}
return vector<int>(resultSet.begin(), resultSet.end());
}
};class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> numsSet(nums1.begin(), nums1.end());
unordered_set<int> resultSet;
for (int num : nums2) {
if (numsSet.find(num) != numsSet.end()) {
resultSet.insert(num);
}
}
return vector<int>(resultSet.begin(), resultSet.end());
}
};unordered_set 可以通过迭代器区间直接初始化:
unordered_set<int> numsSet(nums.begin(), nums.end());unordered_set<int> numsSet(nums.begin(), nums.end());2026-08-17(周一)
哈希表(二)
四、快乐数
- 题目:202. 快乐数
- 核心问题:计算各位数字的平方和时,结果可能进入循环。
- 集合判重:使用
unordered_set保存已经出现过的平方和。- 如果平方和变为 1,则原数是快乐数。
- 如果某个平方和再次出现,则计算进入无限循环,原数不是快乐数。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
// 计算各位数字的平方和
int getSum(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> seen;
while (true) {
int sum = getSum(n);
if (sum == 1) {
return true;
}
// 平方和再次出现,说明已经进入循环
if (seen.find(sum) != seen.end()) {
return false;
}
seen.insert(sum);
n = sum;
}
}
};class Solution {
public:
// 计算各位数字的平方和
int getSum(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> seen;
while (true) {
int sum = getSum(n);
if (sum == 1) {
return true;
}
// 平方和再次出现,说明已经进入循环
if (seen.find(sum) != seen.end()) {
return false;
}
seen.insert(sum);
n = sum;
}
}
};五、两数之和
- 题目:1. 两数之和
- 为什么不使用数组:数值范围可能很大而元素数量较少,直接建立数组会浪费内存。
- 为什么不使用
set:不仅需要判断目标元素是否存在,还需要保存该元素对应的下标。 - 映射哈希:使用
unordered_map存储“元素值 → 下标”。遍历当前元素nums[i]时,在哈希表中查找补数target - nums[i]。 - 平均时间复杂度:
- 空间复杂度:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numToIndex;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
auto iter = numToIndex.find(complement);
if (iter != numToIndex.end()) {
return {iter->second, i};
}
// 未找到匹配项,记录当前元素及其下标
numToIndex.emplace(nums[i], i);
}
return {};
}
};class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numToIndex;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
auto iter = numToIndex.find(complement);
if (iter != numToIndex.end()) {
return {iter->second, i};
}
// 未找到匹配项,记录当前元素及其下标
numToIndex.emplace(nums[i], i);
}
return {};
}
};六、四数相加 II
- 题目:454. 四数相加 II
- 分组哈希:将四个数组分为两组,把四层枚举降为两次两层枚举。
- 解题步骤:
- 使用
unordered_map统计所有a + b出现的次数,其中键为两数之和,值为出现次数。 - 遍历数组 C 与 D,计算
c + d。 - 如果
-(c + d)存在于哈希表中,将其出现次数累加到结果。
- 使用
- 平均时间复杂度:
- 空间复杂度:
class Solution {
public:
int fourSumCount(
vector<int>& A,
vector<int>& B,
vector<int>& C,
vector<int>& D
) {
// key:a + b;value:该和出现的次数
unordered_map<int, int> sumCount;
for (int a : A) {
for (int b : B) {
sumCount[a + b]++;
}
}
int count = 0;
for (int c : C) {
for (int d : D) {
auto iter = sumCount.find(-(c + d));
if (iter != sumCount.end()) {
count += iter->second;
}
}
}
return count;
}
};class Solution {
public:
int fourSumCount(
vector<int>& A,
vector<int>& B,
vector<int>& C,
vector<int>& D
) {
// key:a + b;value:该和出现的次数
unordered_map<int, int> sumCount;
for (int a : A) {
for (int b : B) {
sumCount[a + b]++;
}
}
int count = 0;
for (int c : C) {
for (int d : D) {
auto iter = sumCount.find(-(c + d));
if (iter != sumCount.end()) {
count += iter->second;
}
}
}
return count;
}
};2026-08-18(周二)
哈希表(三)
七、赎金信
- 题目:383. 赎金信
- 暴力解法:使用两层
for循环逐一匹配字符,时间复杂度为 。 - 数组哈希:使用长度为 26 的数组记录
magazine中每个字母的出现次数,再遍历ransomNote逐个消耗。- 如果
ransomNote比magazine更长,可以直接返回false。 - 如果某个字符的剩余次数小于 0,说明
magazine无法提供足够的字符。
- 如果
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if (ransomNote.size() > magazine.size()) {
return false;
}
int record[26] = {0};
for (char ch : magazine) {
record[ch - 'a']++;
}
for (char ch : ransomNote) {
record[ch - 'a']--;
if (record[ch - 'a'] < 0) {
return false;
}
}
return true;
}
};class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if (ransomNote.size() > magazine.size()) {
return false;
}
int record[26] = {0};
for (char ch : magazine) {
record[ch - 'a']++;
}
for (char ch : ransomNote) {
record[ch - 'a']--;
if (record[ch - 'a'] < 0) {
return false;
}
}
return true;
}
};八、三数之和
- 题目:15. 三数之和
- 参考:三数之和(代码随想录)
- 排序与双指针:
- 将数组排序。
- 使用一层
for循环固定a = nums[i]。 - 令
left = i + 1、right = nums.size() - 1,分别表示b与c。 - 当三数之和大于 0 时左移
right;小于 0 时右移left;等于 0 时记录答案并跳过重复元素。
- 去重原则:
- 对
a去重时,应与前一个元素比较;如果与后一个元素比较,会漏掉[-1, -1, 2]。 - 对
b与c去重应在找到有效三元组后进行,否则可能漏掉[0, 0, 0]。
- 对
- 时间复杂度:
- 额外空间复杂度:,不计返回结果,主要来自排序
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
// 最小元素已经大于 0,不可能再得到和为 0 的三元组
if (nums[i] > 0) {
break;
}
// 对固定元素 a 去重
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
result.push_back({nums[i], nums[left], nums[right]});
// 对 b 与 c 去重
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}
}
}
return result;
}
};class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
// 最小元素已经大于 0,不可能再得到和为 0 的三元组
if (nums[i] > 0) {
break;
}
// 对固定元素 a 去重
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
result.push_back({nums[i], nums[left], nums[right]});
// 对 b 与 c 去重
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}
}
}
return result;
}
};这道题的代码较长,重点记住“排序—固定一个数—双指针收缩—命中后去重”这一固定框架。
九、四数之和
- 题目:18. 四数之和
- 核心思路:三数之和使用一层循环固定一个数;四数之和使用两层循环固定两个数,再在剩余区间内使用双指针。
- 固定
nums[k]与nums[i] - 令
left = i + 1、right = nums.size() - 1 - 寻找满足
nums[k] + nums[i] + nums[left] + nums[right] == target的四元组
- 固定
- 通用扩展:五数之和、六数之和等问题,也可以继续增加固定元素的循环层数。
- 注意溢出:计算四数之和时使用
long long。 - 时间复杂度:
- 额外空间复杂度:,不计返回结果,主要来自排序
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int k = 0; k < nums.size(); k++) {
// 一级剪枝
if (nums[k] > target && nums[k] >= 0) {
break;
}
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
for (int i = k + 1; i < nums.size(); i++) {
// 二级剪枝
long long fixedSum = static_cast<long long>(nums[k]) + nums[i];
if (fixedSum > target && fixedSum >= 0) {
break;
}
if (i > k + 1 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
long long sum = static_cast<long long>(nums[k])
+ nums[i]
+ nums[left]
+ nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.push_back({
nums[k], nums[i], nums[left], nums[right]
});
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}
}
}
}
return result;
}
};class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int k = 0; k < nums.size(); k++) {
// 一级剪枝
if (nums[k] > target && nums[k] >= 0) {
break;
}
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
for (int i = k + 1; i < nums.size(); i++) {
// 二级剪枝
long long fixedSum = static_cast<long long>(nums[k]) + nums[i];
if (fixedSum > target && fixedSum >= 0) {
break;
}
if (i > k + 1 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
long long sum = static_cast<long long>(nums[k])
+ nums[i]
+ nums[left]
+ nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.push_back({
nums[k], nums[i], nums[left], nums[right]
});
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}
}
}
}
return result;
}
};十、哈希表总结
核心作用
- 快速判断元素是否出现
- 统计元素出现频率
- 建立元素与下标、计数等信息之间的映射
常用结构选择
- 数组:数值或字符范围较小且固定,例如字母异位词、赎金信
set/unordered_set:只需要判断元素是否存在或进行去重,例如两个数组的交集、快乐数map/unordered_map:需要保存<key, value>映射,例如元素到下标、两数之和到出现次数
相关解题模式
- 当哈希法的去重逻辑较复杂时,可以考虑“排序 + 双指针”,例如三数之和与四数之和。
2026-08-19(周三)
字符串(一)
一、反转字符串
- 题目:344. 反转字符串
- 双指针法:分别在字符串首尾设置
left和right,交换两个指针指向的字符,然后同时向中间移动,直到二者相遇。 - 时间复杂度:
- 空间复杂度:
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = static_cast<int>(s.size()) - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
};class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = static_cast<int>(s.size()) - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
};二、反转字符串 II
- 题目:541. 反转字符串 II
- 分段处理:每次令
i += 2 * k,处理当前 个字符中的前 个字符。- 剩余字符不少于 个:反转前 个字符。
- 剩余字符少于 个:反转全部剩余字符。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
void reverseRange(string& s, int start, int end) {
while (start < end) {
swap(s[start], s[end]);
start++;
end--;
}
}
string reverseStr(string s, int k) {
int n = s.size();
for (int i = 0; i < n; i += 2 * k) {
// 取前 k 个字符;不足 k 个时,反转全部剩余字符
int end = min(i + k - 1, n - 1);
reverseRange(s, i, end);
}
return s;
}
};class Solution {
public:
void reverseRange(string& s, int start, int end) {
while (start < end) {
swap(s[start], s[end]);
start++;
end--;
}
}
string reverseStr(string s, int k) {
int n = s.size();
for (int i = 0; i < n; i += 2 * k) {
// 取前 k 个字符;不足 k 个时,反转全部剩余字符
int end = min(i + k - 1, n - 1);
reverseRange(s, i, end);
}
return s;
}
};三、替换数字
- 题目:54. 替换数字
- 核心思路:先统计数字字符的数量,将字符串扩充到替换后的长度,再使用双指针从后向前填充。
oldIndex指向原字符串末尾。newIndex指向扩容后字符串末尾。- 普通字符直接复制;数字字符倒序写入
"number"。
- 为什么从后向前填充:
- 可以直接在原字符串上操作,无需额外申请一个结果字符串。
- 避免从前向后插入字符时,反复移动后续所有元素。
- 时间复杂度:
- 额外空间复杂度:,不计字符串扩容后的必要空间
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while (cin >> s) {
int digitCount = 0;
for (char ch : s) {
if (ch >= '0' && ch <= '9') {
digitCount++;
}
}
int oldIndex = static_cast<int>(s.size()) - 1;
// 一个数字替换为 6 个字符,字符串长度因此额外增加 5
s.resize(s.size() + digitCount * 5);
int newIndex = static_cast<int>(s.size()) - 1;
while (oldIndex >= 0) {
if (s[oldIndex] >= '0' && s[oldIndex] <= '9') {
s[newIndex--] = 'r';
s[newIndex--] = 'e';
s[newIndex--] = 'b';
s[newIndex--] = 'm';
s[newIndex--] = 'u';
s[newIndex--] = 'n';
} else {
s[newIndex--] = s[oldIndex];
}
oldIndex--;
}
cout << s << endl;
}
return 0;
}#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while (cin >> s) {
int digitCount = 0;
for (char ch : s) {
if (ch >= '0' && ch <= '9') {
digitCount++;
}
}
int oldIndex = static_cast<int>(s.size()) - 1;
// 一个数字替换为 6 个字符,字符串长度因此额外增加 5
s.resize(s.size() + digitCount * 5);
int newIndex = static_cast<int>(s.size()) - 1;
while (oldIndex >= 0) {
if (s[oldIndex] >= '0' && s[oldIndex] <= '9') {
s[newIndex--] = 'r';
s[newIndex--] = 'e';
s[newIndex--] = 'b';
s[newIndex--] = 'm';
s[newIndex--] = 'u';
s[newIndex--] = 'n';
} else {
s[newIndex--] = s[oldIndex];
}
oldIndex--;
}
cout << s << endl;
}
return 0;
}2026-08-29(周六)
字符串(三)
六、实现 strStr
- 题目:28. 找出字符串中第一个匹配项的下标
- KMP 的核心作用:当字符失配时,利用已经匹配的前后缀信息移动模式串,避免文本串回退并从头匹配。
- 前缀表:对于模式串的每个位置
i,记录子串[0, i]中最长相等真前缀与真后缀的信息。 - 本实现的
next定义:next[i] = j,其中j是最长相等前后缀的最后一个下标。- 对应的最长相等前后缀长度为
j + 1。 - 当失配发生时,令
j = next[j],继续尝试更短的相等前后缀。
- 时间复杂度:
- 空间复杂度:,其中 为模式串长度
class Solution {
public:
void getNext(vector<int>& next, const string& pattern) {
int j = -1;
next[0] = -1;
// i 从 1 开始,j 表示最长相等前后缀的最后一个下标
for (int i = 1; i < pattern.size(); i++) {
while (j >= 0 && pattern[i] != pattern[j + 1]) {
j = next[j];
}
if (pattern[i] == pattern[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
vector<int> next(needle.size());
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
// 模式串全部匹配完成
if (j == static_cast<int>(needle.size()) - 1) {
return i - static_cast<int>(needle.size()) + 1;
}
}
return -1;
}
};class Solution {
public:
void getNext(vector<int>& next, const string& pattern) {
int j = -1;
next[0] = -1;
// i 从 1 开始,j 表示最长相等前后缀的最后一个下标
for (int i = 1; i < pattern.size(); i++) {
while (j >= 0 && pattern[i] != pattern[j + 1]) {
j = next[j];
}
if (pattern[i] == pattern[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
vector<int> next(needle.size());
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
// 模式串全部匹配完成
if (j == static_cast<int>(needle.size()) - 1) {
return i - static_cast<int>(needle.size()) + 1;
}
}
return -1;
}
};核心记忆:文本串不回退;模式串根据前缀表回退到可复用的匹配位置。
七、重复的子字符串
- 题目:459. 重复的子字符串
- KMP 判断方法:
- 计算字符串末尾位置对应的最长相等前后缀长度
longestPrefixSuffix。 - 候选最小重复单元长度为
period = n - longestPrefixSuffix。 - 如果最长相等前后缀存在,且
n % period == 0,则字符串可由该重复单元构成。
- 计算字符串末尾位置对应的最长相等前后缀长度
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
void getNext(vector<int>& next, const string& s) {
int j = -1;
next[0] = -1;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
if (s.empty()) {
return false;
}
vector<int> next(s.size());
getNext(next, s);
int n = s.size();
int longestPrefixSuffix = next[n - 1] + 1;
int period = n - longestPrefixSuffix;
return longestPrefixSuffix > 0 && n % period == 0;
}
};class Solution {
public:
void getNext(vector<int>& next, const string& s) {
int j = -1;
next[0] = -1;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
if (s.empty()) {
return false;
}
vector<int> next(s.size());
getNext(next, s);
int n = s.size();
int longestPrefixSuffix = next[n - 1] + 1;
int period = n - longestPrefixSuffix;
return longestPrefixSuffix > 0 && n % period == 0;
}
};八、字符串总结
基本概念
- 字符串是由若干字符组成的有限序列,也可以理解为字符数组。
常见解题方法
- 双指针:从首尾向中间移动,完成字符串反转。
- 扩容与倒序填充:在原字符串中替换长度增加的内容,避免反复移动元素。
- 整体反转与局部反转:处理单词顺序反转、字符串旋转等问题。
- 快慢指针:移除多余空格并压缩字符串。
- KMP:利用最长相等前后缀信息,高效完成字符串匹配与周期判断。
2026-08-31(周一)
栈与队列(一)
一、栈与队列理论基础
基本特性
- 队列(Queue):先进先出,简称 FIFO(First In, First Out)。
- 栈(Stack):先进后出,简称 LIFO(Last In, First Out)。
容器适配器
std::stack 和 std::queue 本身不直接负责存储数据,而是调用底层容器完成操作,并向外提供统一且受限的接口。因此,它们在 STL 中被归类为 container adapter(容器适配器),而不是独立容器。
std::stack默认使用deque作为底层容器,也可以使用满足操作要求的vector或list。std::queue默认使用deque作为底层容器,也可以使用支持首尾操作的list。- 底层既可能采用连续存储结构,也可能采用链式存储结构,具体取决于选用的容器。
二、用栈实现队列
- 题目:232. 用栈实现队列
- 核心设计:使用两个栈模拟队列。
stackIn:负责接收新元素。stackOut:负责弹出队首元素。
- 数据转移规则:只有当
stackOut为空时,才将stackIn中的全部元素依次转移到stackOut;转移后元素顺序被反转,最早进入的元素位于栈顶。 - 判空规则:只有输入栈与输出栈均为空时,模拟队列才为空。
push:pop/peek:均摊- 空间复杂度:
class MyQueue {
public:
MyQueue() = default;
void push(int x) {
stackIn.push(x);
}
int pop() {
transferIfNeeded();
int result = stackOut.top();
stackOut.pop();
return result;
}
int peek() {
transferIfNeeded();
return stackOut.top();
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
private:
stack<int> stackIn;
stack<int> stackOut;
void transferIfNeeded() {
if (!stackOut.empty()) {
return;
}
while (!stackIn.empty()) {
stackOut.push(stackIn.top());
stackIn.pop();
}
}
};class MyQueue {
public:
MyQueue() = default;
void push(int x) {
stackIn.push(x);
}
int pop() {
transferIfNeeded();
int result = stackOut.top();
stackOut.pop();
return result;
}
int peek() {
transferIfNeeded();
return stackOut.top();
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
private:
stack<int> stackIn;
stack<int> stackOut;
void transferIfNeeded() {
if (!stackOut.empty()) {
return;
}
while (!stackIn.empty()) {
stackOut.push(stackIn.top());
stackIn.pop();
}
}
};每个元素最多经历一次进入
stackIn、一次转移到stackOut和一次弹出,因此pop与peek的均摊复杂度为 。
三、用队列实现栈
- 题目:225. 用队列实现栈
- 核心问题:队列是先进先出,直接在两个队列之间转移元素不会改变顺序,因此需要将主队列中除最后一个元素外的所有元素移入辅助队列。
- 双队列实现:
queue1保存栈中的有效元素。- 执行
pop或top时,将queue1中除最后一个元素外的所有元素转移到queue2。 queue1中最后留下的元素就是栈顶。- 操作完成后交换两个队列,使
queue1重新成为主队列。
push:pop/top:- 空间复杂度:
class MyStack {
public:
MyStack() = default;
void push(int x) {
queue1.push(x);
}
int pop() {
moveExceptLast();
int result = queue1.front();
queue1.pop();
queue1.swap(queue2);
return result;
}
int top() {
moveExceptLast();
int result = queue1.front();
queue2.push(result);
queue1.pop();
queue1.swap(queue2);
return result;
}
bool empty() {
return queue1.empty();
}
private:
queue<int> queue1;
queue<int> queue2;
// 将除最后一个元素外的其他元素转移到辅助队列
void moveExceptLast() {
while (queue1.size() > 1) {
queue2.push(queue1.front());
queue1.pop();
}
}
};class MyStack {
public:
MyStack() = default;
void push(int x) {
queue1.push(x);
}
int pop() {
moveExceptLast();
int result = queue1.front();
queue1.pop();
queue1.swap(queue2);
return result;
}
int top() {
moveExceptLast();
int result = queue1.front();
queue2.push(result);
queue1.pop();
queue1.swap(queue2);
return result;
}
bool empty() {
return queue1.empty();
}
private:
queue<int> queue1;
queue<int> queue2;
// 将除最后一个元素外的其他元素转移到辅助队列
void moveExceptLast() {
while (queue1.size() > 1) {
queue2.push(queue1.front());
queue1.pop();
}
}
};2026-09-01(周二)
栈与队列(二)
四、有效的括号
- 题目:20. 有效的括号
- 核心方法:遇到左括号时,将其对应的右括号压入栈;遇到右括号时,检查它是否与栈顶的预期字符一致。
- 三种不匹配情况:
- 字符串遍历结束后栈仍不为空:存在没有右括号与之匹配的左括号。
- 遇到右括号时栈顶字符不同:括号类型不匹配。
- 遇到右括号时栈已经为空:该右括号没有对应的左括号。
- 如果字符串长度为奇数,可以直接判定为无效。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) {
return false;
}
stack<char> expected;
for (char ch : s) {
if (ch == '(') {
expected.push(')');
} else if (ch == '{') {
expected.push('}');
} else if (ch == '[') {
expected.push(']');
} else {
if (expected.empty() || expected.top() != ch) {
return false;
}
expected.pop();
}
}
return expected.empty();
}
};class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) {
return false;
}
stack<char> expected;
for (char ch : s) {
if (ch == '(') {
expected.push(')');
} else if (ch == '{') {
expected.push('}');
} else if (ch == '[') {
expected.push(']');
} else {
if (expected.empty() || expected.top() != ch) {
return false;
}
expected.pop();
}
}
return expected.empty();
}
};五、删除字符串中的所有相邻重复项
- 题目:1047. 删除字符串中的所有相邻重复项
- 栈模拟消除:
- 如果栈为空或当前字符与栈顶不同,将当前字符压入栈。
- 如果当前字符与栈顶相同,弹出栈顶,使这一对相邻重复字符相互抵消。
- 遍历结束后,栈中保留的字符就是最终结果的逆序。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
string removeDuplicates(string s) {
stack<char> remaining;
for (char ch : s) {
if (remaining.empty() || remaining.top() != ch) {
remaining.push(ch);
} else {
remaining.pop();
}
}
string result;
result.reserve(remaining.size());
while (!remaining.empty()) {
result.push_back(remaining.top());
remaining.pop();
}
reverse(result.begin(), result.end());
return result;
}
};class Solution {
public:
string removeDuplicates(string s) {
stack<char> remaining;
for (char ch : s) {
if (remaining.empty() || remaining.top() != ch) {
remaining.push(ch);
} else {
remaining.pop();
}
}
string result;
result.reserve(remaining.size());
while (!remaining.empty()) {
result.push_back(remaining.top());
remaining.pop();
}
reverse(result.begin(), result.end());
return result;
}
};六、逆波兰表达式求值
- 题目:150. 逆波兰表达式求值
- 栈求值:
- 遇到数字时,将其压入栈。
- 遇到运算符时,依次弹出右操作数与左操作数,计算后将结果重新压入栈。
- 遍历结束后,栈顶元素就是表达式结果。
- 操作数顺序:第一次弹出的是右操作数,第二次弹出的是左操作数;减法与除法不能颠倒。
- 这一过程与删除相邻重复项类似:都根据当前元素与栈顶状态进行“消除”或合并。
- 时间复杂度:
- 空间复杂度:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> operands;
for (const string& token : tokens) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
long long right = operands.top();
operands.pop();
long long left = operands.top();
operands.pop();
if (token == "+") {
operands.push(left + right);
} else if (token == "-") {
operands.push(left - right);
} else if (token == "*") {
operands.push(left * right);
} else {
operands.push(left / right);
}
} else {
operands.push(stoll(token));
}
}
return static_cast<int>(operands.top());
}
};class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> operands;
for (const string& token : tokens) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
long long right = operands.top();
operands.pop();
long long left = operands.top();
operands.pop();
if (token == "+") {
operands.push(left + right);
} else if (token == "-") {
operands.push(left - right);
} else if (token == "*") {
operands.push(left * right);
} else {
operands.push(left / right);
}
} else {
operands.push(stoll(token));
}
}
return static_cast<int>(operands.top());
}
};2026-09-02(周三)
栈与队列(三)
七、滑动窗口最大值
- 题目:239. 滑动窗口最大值
- 单调队列:只维护仍有可能成为窗口最大值的元素,并让队列从队首到队尾保持单调不增。
- 入队规则:新元素入队前,将队尾所有小于新元素的值弹出;这些较小元素不可能再成为后续窗口的最大值。
- 出队规则:窗口左侧元素离开时,只有当它等于队首元素时才弹出队首。
- 查询最大值:队首始终是当前窗口最大值。
- 时间复杂度:,每个元素至多入队和出队一次
- 空间复杂度:
class Solution {
private:
class MonotonicQueue {
public:
void pop(int value) {
if (!values.empty() && values.front() == value) {
values.pop_front();
}
}
void push(int value) {
while (!values.empty() && values.back() < value) {
values.pop_back();
}
values.push_back(value);
}
int max() const {
return values.front();
}
private:
deque<int> values;
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> result;
result.reserve(nums.size() - k + 1);
for (int i = 0; i < k; i++) {
window.push(nums[i]);
}
result.push_back(window.max());
for (int i = k; i < nums.size(); i++) {
window.pop(nums[i - k]);
window.push(nums[i]);
result.push_back(window.max());
}
return result;
}
};class Solution {
private:
class MonotonicQueue {
public:
void pop(int value) {
if (!values.empty() && values.front() == value) {
values.pop_front();
}
}
void push(int value) {
while (!values.empty() && values.back() < value) {
values.pop_back();
}
values.push_back(value);
}
int max() const {
return values.front();
}
private:
deque<int> values;
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> result;
result.reserve(nums.size() - k + 1);
for (int i = 0; i < k; i++) {
window.push(nums[i]);
}
result.push_back(window.max());
for (int i = k; i < nums.size(); i++) {
window.pop(nums[i - k]);
window.push(nums[i]);
result.push_back(window.max());
}
return result;
}
};八、前 K 个高频元素
- 题目:347. 前 K 个高频元素
- 频率统计:使用
unordered_map记录每个元素的出现次数。 - 小顶堆:维护一个大小不超过 的小顶堆,堆顶始终是当前候选项中频率最低的元素。
- 将“频率—元素”对压入堆中。
- 当堆大小超过 时,弹出频率最低的元素。
- 遍历结束后,堆中保留的就是频率最高的 个元素。
- 时间复杂度:,其中 为不同元素的数量
- 空间复杂度:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> frequency;
for (int num : nums) {
frequency[num]++;
}
// pair.first 为频率,pair.second 为元素;使用小顶堆
priority_queue<
pair<int, int>,
vector<pair<int, int>>,
greater<pair<int, int>>
> minHeap;
for (const auto& [num, freq] : frequency) {
minHeap.push({freq, num});
if (minHeap.size() > k) {
minHeap.pop();
}
}
vector<int> result;
result.reserve(k);
while (!minHeap.empty()) {
result.push_back(minHeap.top().second);
minHeap.pop();
}
return result;
}
};class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> frequency;
for (int num : nums) {
frequency[num]++;
}
// pair.first 为频率,pair.second 为元素;使用小顶堆
priority_queue<
pair<int, int>,
vector<pair<int, int>>,
greater<pair<int, int>>
> minHeap;
for (const auto& [num, freq] : frequency) {
minHeap.push({freq, num});
if (minHeap.size() > k) {
minHeap.pop();
}
}
vector<int> result;
result.reserve(k);
while (!minHeap.empty()) {
result.push_back(minHeap.top().second);
minHeap.pop();
}
return result;
}
};若题目不要求按频率降序返回,直接依次弹出小顶堆即可;此时结果中的顺序不固定。
九、栈与队列总结
常见问题
stack和queue是容器吗?- 不是。它们是容器适配器,通过限制底层容器的接口来表现栈或队列的行为。
- 它们属于哪个版本的 STL?
- C++ 标准只规定接口与行为,具体实现取决于所用的标准库,例如 GCC 的 libstdc++、Clang 的 libc++ 或 MSVC STL;课程中常以 SGI STL 为实现参考。
- 它们通常如何实现?
stack与queue默认均以deque作为底层容器,也可以按接口要求替换其他容器。
- 它们提供迭代器吗?
- 不提供。容器适配器只暴露栈顶、队首、队尾等受限接口,不能直接遍历内部元素。
面试问题:栈中元素在内存里连续吗?
- 不一定。
stack是容器适配器,元素的内存布局取决于底层容器。 - 默认底层容器是
deque;deque采用分段连续存储,整体内存并不连续。 - 如果显式使用
vector作为底层容器,元素才是连续存储的。
经典题型
- 栈:结构模拟、括号匹配、相邻元素消除、逆波兰表达式求值
- 队列:滑动窗口最大值
- 优先队列:前 K 个高频元素
堆的定义
- 堆是一棵完全二叉树。
- 大顶堆:每个节点的值都不小于其子节点。
- 小顶堆:每个节点的值都不大于其子节点。
2026-09-03(周四)
二叉树(一)
二叉树专题主要覆盖递归、迭代、层序遍历、属性计算、树的构造、二叉搜索树以及最近公共祖先等内容。
一、二叉树理论基础
常见类型
- 满二叉树:只有度为 0 和度为 2 的节点,并且所有叶子节点都在同一层。若共有 层,则节点总数为 。
- 完全二叉树:除最底层外,其余各层节点数均达到最大值;最底层的节点从左到右连续排列。若最底层是第 层,则该层节点数介于 1 与 之间。
- 二叉搜索树(BST):一种有序二叉树。
- 左子树中所有节点的值均小于根节点的值。
- 右子树中所有节点的值均大于根节点的值。
- 左右子树也分别是二叉搜索树。
- 平衡二叉搜索树(AVL 树):空树,或任意节点左右子树高度差的绝对值不超过 1,并且左右子树也都是平衡二叉树。
C++ 标准规定
map、set、multimap和multiset的主要操作复杂度为 ,常见实现采用红黑树;unordered_map和unordered_set通常使用哈希表,平均查询与增删复杂度为 。
存储方式
- 链式存储:每个节点通过指针连接左右孩子。
- 顺序存储:使用数组保存节点。采用从 0 开始的下标时,若父节点下标为 :
- 左孩子下标为
- 右孩子下标为
遍历方式
- 深度优先遍历(DFS):沿一条路径向深处访问,遇到叶子节点后回退。
- 前序遍历:中 → 左 → 右
- 中序遍历:左 → 中 → 右
- 后序遍历:左 → 右 → 中
- 广度优先遍历(BFS):按层从上到下遍历,也称层序遍历。
前序、中序和后序中的“前、中、后”,指的是根节点相对于左右子树的处理顺序。DFS 通常使用递归或栈实现,BFS 通常使用队列实现。
节点定义
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};二、二叉树的递归遍历
- 题目:144. 二叉树的前序遍历
- 题目:94. 二叉树的中序遍历
- 题目:145. 二叉树的后序遍历
递归算法的三个要素
- 确定参数和返回值:明确递归过程中需要传递和处理的数据,以及函数应返回什么。
- 确定终止条件:避免递归无限进行并导致调用栈溢出;遍历二叉树时,通常在当前节点为
nullptr时返回。 - 确定单层递归逻辑:明确当前层应处理什么,以及左右子树的递归调用顺序。
// 前序遍历:中 → 左 → 右
void preorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
result.push_back(node->val);
preorder(node->left, result);
preorder(node->right, result);
}
// 中序遍历:左 → 中 → 右
void inorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
inorder(node->left, result);
result.push_back(node->val);
inorder(node->right, result);
}
// 后序遍历:左 → 右 → 中
void postorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
postorder(node->left, result);
postorder(node->right, result);
result.push_back(node->val);
}// 前序遍历:中 → 左 → 右
void preorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
result.push_back(node->val);
preorder(node->left, result);
preorder(node->right, result);
}
// 中序遍历:左 → 中 → 右
void inorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
inorder(node->left, result);
result.push_back(node->val);
inorder(node->right, result);
}
// 后序遍历:左 → 右 → 中
void postorder(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
postorder(node->left, result);
postorder(node->right, result);
result.push_back(node->val);
}- 时间复杂度:
- 空间复杂度:,来自递归调用栈;最坏情况下为
三、二叉树的迭代遍历
使用栈可以迭代实现二叉树的前序、中序和后序遍历。
前序遍历
前序顺序是“中 → 左 → 右”。由于栈是先进后出,因此处理当前节点后,应先压入右孩子,再压入左孩子。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
result.push_back(node->val);
if (node->right != nullptr) {
nodes.push(node->right);
}
if (node->left != nullptr) {
nodes.push(node->left);
}
}
return result;
}
};class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
result.push_back(node->val);
if (node->right != nullptr) {
nodes.push(node->right);
}
if (node->left != nullptr) {
nodes.push(node->left);
}
}
return result;
}
};中序遍历
中序顺序是“左 → 中 → 右”,访问节点的顺序与处理节点值的顺序不一致。因此,使用指针负责沿左侧访问节点,使用栈保存尚未处理的节点。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> nodes;
TreeNode* current = root;
while (current != nullptr || !nodes.empty()) {
if (current != nullptr) {
nodes.push(current);
current = current->left;
} else {
current = nodes.top();
nodes.pop();
result.push_back(current->val);
current = current->right;
}
}
return result;
}
};class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> nodes;
TreeNode* current = root;
while (current != nullptr || !nodes.empty()) {
if (current != nullptr) {
nodes.push(current);
current = current->left;
} else {
current = nodes.top();
nodes.pop();
result.push_back(current->val);
current = current->right;
}
}
return result;
}
};后序遍历
将前序遍历的入栈顺序调整为先压入左孩子、再压入右孩子,可以得到“中 → 右 → 左”;最后反转结果,即可得到“左 → 右 → 中”。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
result.push_back(node->val);
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
reverse(result.begin(), result.end());
return result;
}
};class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
result.push_back(node->val);
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
reverse(result.begin(), result.end());
return result;
}
};- 时间复杂度:
- 额外空间复杂度:,最坏情况下为
2026-09-05(周六)
二叉树(三)
九、二叉树的最大深度
本题中的最大深度,是从根节点到最远叶子节点的最长路径上的节点数。
- 节点深度:从根节点到该节点的路径所经过的节点数。
- 节点高度:从该节点到最远叶子节点的路径所经过的节点数。
对整棵树而言,根节点的高度就是树的最大深度。可以使用后序遍历计算高度,也可以使用前序遍历记录深度,或使用层序遍历统计层数。
方法一:后序遍历——计算高度
先得到左右子树的高度,再取较大值并加上当前节点这一层。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
};class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
};- 时间复杂度:
- 空间复杂度:,来自递归调用栈;最坏情况下为
方法二:前序遍历——记录深度
前序遍历在到达节点时更新最大深度。这里将 depth + 1 按值传入下一层,相当于完成了隐式回溯,不需要手动执行 depth++ 和 depth--。
class Solution {
private:
int result = 0;
void getDepth(TreeNode* node, int depth) {
if (node == nullptr) {
return;
}
result = max(result, depth);
getDepth(node->left, depth + 1);
getDepth(node->right, depth + 1);
}
public:
int maxDepth(TreeNode* root) {
getDepth(root, 1);
return result;
}
};class Solution {
private:
int result = 0;
void getDepth(TreeNode* node, int depth) {
if (node == nullptr) {
return;
}
result = max(result, depth);
getDepth(node->left, depth + 1);
getDepth(node->right, depth + 1);
}
public:
int maxDepth(TreeNode* root) {
getDepth(root, 1);
return result;
}
};方法三:层序遍历——统计层数
每处理完一层,深度加一。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int depth = 0;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
++depth;
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return depth;
}
};class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int depth = 0;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
++depth;
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return depth;
}
};- 时间复杂度:
- 空间复杂度:,其中 为二叉树的最大宽度
十、二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数。叶子节点必须同时满足左右孩子均为空。
易错点
如果某个节点只有一棵子树,不能直接使用
min(leftDepth, rightDepth) + 1,因为空子树并没有通向叶子节点。此时必须沿非空子树继续计算。
方法一:后序递归
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if (root->left == nullptr) {
return rightDepth + 1;
}
if (root->right == nullptr) {
return leftDepth + 1;
}
return min(leftDepth, rightDepth) + 1;
}
};class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if (root->left == nullptr) {
return rightDepth + 1;
}
if (root->right == nullptr) {
return leftDepth + 1;
}
return min(leftDepth, rightDepth) + 1;
}
};- 时间复杂度:
- 空间复杂度:,最坏情况下为
方法二:前序递归
到达叶子节点时更新当前最小深度。
class Solution {
private:
int result = INT_MAX;
void getDepth(TreeNode* node, int depth) {
if (node == nullptr) {
return;
}
if (node->left == nullptr && node->right == nullptr) {
result = min(result, depth);
return;
}
getDepth(node->left, depth + 1);
getDepth(node->right, depth + 1);
}
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
getDepth(root, 1);
return result;
}
};class Solution {
private:
int result = INT_MAX;
void getDepth(TreeNode* node, int depth) {
if (node == nullptr) {
return;
}
if (node->left == nullptr && node->right == nullptr) {
result = min(result, depth);
return;
}
getDepth(node->left, depth + 1);
getDepth(node->right, depth + 1);
}
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
getDepth(root, 1);
return result;
}
};方法三:层序遍历
BFS 按层搜索,遇到的第一个叶子节点一定处于最浅的一层,可以立即返回当前深度。
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int depth = 0;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
++depth;
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (node->left == nullptr && node->right == nullptr) {
return depth;
}
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return depth;
}
};class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int depth = 0;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
++depth;
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (node->left == nullptr && node->right == nullptr) {
return depth;
}
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return depth;
}
};- 时间复杂度:最坏为
- 空间复杂度:,其中 为二叉树的最大宽度
十一、完全二叉树的节点个数
方法一:按照普通二叉树递归统计
遍历所有节点即可得到答案。该方法正确且直观,但没有利用完全二叉树的结构性质。
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftCount = countNodes(root->left);
int rightCount = countNodes(root->right);
return leftCount + rightCount + 1;
}
};class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftCount = countNodes(root->left);
int rightCount = countNodes(root->right);
return leftCount + rightCount + 1;
}
};- 时间复杂度:
- 空间复杂度:
方法二:利用完全二叉树性质
对于完全二叉树中的任意子树:
- 分别沿最左路径和最右路径计算深度。
- 如果两者相等,说明当前子树是满二叉树,可直接用 计算节点数。
- 如果两者不等,则继续递归统计左右子树。
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = 0;
int rightDepth = 0;
TreeNode* left = root->left;
while (left != nullptr) {
left = left->left;
++leftDepth;
}
TreeNode* right = root->right;
while (right != nullptr) {
right = right->right;
++rightDepth;
}
if (leftDepth == rightDepth) {
return static_cast<int>((1LL << (leftDepth + 1)) - 1);
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = 0;
int rightDepth = 0;
TreeNode* left = root->left;
while (left != nullptr) {
left = left->left;
++leftDepth;
}
TreeNode* right = root->right;
while (right != nullptr) {
right = right->right;
++rightDepth;
}
if (leftDepth == rightDepth) {
return static_cast<int>((1LL << (leftDepth + 1)) - 1);
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};- 时间复杂度:
- 空间复杂度:,来自递归调用栈
2026-09-07(周一)
二叉树(四)
十二、平衡二叉树
题目:110. 平衡二叉树
平衡二叉树要求每个节点的左右子树高度差不超过 1。判断时需要先得到左右子树的高度,因此适合使用“左 → 右 → 中”的后序遍历。
递归函数有两种返回含义:
- 返回非负数:当前子树平衡,该值表示子树高度。
- 返回
-1:当前子树已经不平衡,可以立即向上返回,无须继续计算。
class Solution {
private:
int getHeight(TreeNode* node) {
if (node == nullptr) {
return 0;
}
int leftHeight = getHeight(node->left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = getHeight(node->right);
if (rightHeight == -1) {
return -1;
}
if (abs(leftHeight - rightHeight) > 1) {
return -1;
}
return max(leftHeight, rightHeight) + 1;
}
public:
bool isBalanced(TreeNode* root) {
return getHeight(root) != -1;
}
};class Solution {
private:
int getHeight(TreeNode* node) {
if (node == nullptr) {
return 0;
}
int leftHeight = getHeight(node->left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = getHeight(node->right);
if (rightHeight == -1) {
return -1;
}
if (abs(leftHeight - rightHeight) > 1) {
return -1;
}
return max(leftHeight, rightHeight) + 1;
}
public:
bool isBalanced(TreeNode* root) {
return getHeight(root) != -1;
}
};- 时间复杂度:,每个节点最多访问一次
- 空间复杂度:,来自递归调用栈;最坏情况下为
十三、二叉树的所有路径
题目要求记录从根节点到每个叶子节点的路径。使用前序遍历可以按“父节点 → 子节点”的方向构造路径;完成一条路径后,需要通过回溯撤销当前节点,再进入其他分支。
回溯过程可以概括为:
- 将当前节点加入
path。 - 如果到达叶子节点,生成路径字符串并保存。
- 递归遍历左右子树。
- 执行
path.pop_back(),撤销当前节点的选择。
class Solution {
private:
void traversal(
TreeNode* node,
vector<int>& path,
vector<string>& result
) {
path.push_back(node->val);
if (node->left == nullptr && node->right == nullptr) {
string currentPath = to_string(path[0]);
for (size_t i = 1; i < path.size(); ++i) {
currentPath += "->" + to_string(path[i]);
}
result.push_back(currentPath);
} else {
if (node->left != nullptr) {
traversal(node->left, path, result);
}
if (node->right != nullptr) {
traversal(node->right, path, result);
}
}
path.pop_back();
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (root == nullptr) {
return result;
}
vector<int> path;
traversal(root, path, result);
return result;
}
};class Solution {
private:
void traversal(
TreeNode* node,
vector<int>& path,
vector<string>& result
) {
path.push_back(node->val);
if (node->left == nullptr && node->right == nullptr) {
string currentPath = to_string(path[0]);
for (size_t i = 1; i < path.size(); ++i) {
currentPath += "->" + to_string(path[i]);
}
result.push_back(currentPath);
} else {
if (node->left != nullptr) {
traversal(node->left, path, result);
}
if (node->right != nullptr) {
traversal(node->right, path, result);
}
}
path.pop_back();
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (root == nullptr) {
return result;
}
vector<int> path;
traversal(root, path, result);
return result;
}
};- 时间复杂度:,其中 为所有输出路径的总长度;最坏情况下可达
- 空间复杂度:不计输出结果为 ,用于递归调用栈和当前路径
十四、左叶子之和
题目:404. 左叶子之和
左叶子不是“二叉树左侧的节点”,而是某个父节点的左孩子,并且该左孩子没有任何孩子。当前节点无法独立判断自己是不是左叶子,通常需要由父节点检查其左孩子:
node->left != nullptr
&& node->left->left == nullptr
&& node->left->right == nullptrnode->left != nullptr
&& node->left->left == nullptr
&& node->left->right == nullptr易错点
根节点即使没有孩子,也不是左叶子,因为它不是任何节点的左孩子。
方法一:递归遍历
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int result = 0;
if (root->left != nullptr
&& root->left->left == nullptr
&& root->left->right == nullptr) {
result += root->left->val;
} else {
result += sumOfLeftLeaves(root->left);
}
result += sumOfLeftLeaves(root->right);
return result;
}
};class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int result = 0;
if (root->left != nullptr
&& root->left->left == nullptr
&& root->left->right == nullptr) {
result += root->left->val;
} else {
result += sumOfLeftLeaves(root->left);
}
result += sumOfLeftLeaves(root->right);
return result;
}
};- 时间复杂度:
- 空间复杂度:,来自递归调用栈
方法二:迭代遍历
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int result = 0;
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
if (node->left != nullptr
&& node->left->left == nullptr
&& node->left->right == nullptr) {
result += node->left->val;
}
if (node->right != nullptr) {
nodes.push(node->right);
}
if (node->left != nullptr) {
nodes.push(node->left);
}
}
return result;
}
};class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int result = 0;
stack<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* node = nodes.top();
nodes.pop();
if (node->left != nullptr
&& node->left->left == nullptr
&& node->left->right == nullptr) {
result += node->left->val;
}
if (node->right != nullptr) {
nodes.push(node->right);
}
if (node->left != nullptr) {
nodes.push(node->left);
}
}
return result;
}
};- 时间复杂度:
- 空间复杂度:,最坏情况下为
2026-09-08(周二)
二叉树(五)
十五、找树左下角的值
题目:513. 找树左下角的值
目标是找到二叉树最底层最左边节点的值。使用层序遍历时,每层第一个出队的节点就是该层最左侧节点;不断更新结果,遍历结束后保留的就是最后一层最左侧节点的值。
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int result = root->val;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (i == 0) {
result = node->val;
}
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return result;
}
};class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int result = root->val;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
int levelSize = nodes.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode* node = nodes.front();
nodes.pop();
if (i == 0) {
result = node->val;
}
if (node->left != nullptr) {
nodes.push(node->left);
}
if (node->right != nullptr) {
nodes.push(node->right);
}
}
}
return result;
}
};- 时间复杂度:
- 空间复杂度:,其中 为二叉树的最大宽度
十六、路径总和
题目:112. 路径总和
判断是否存在一条从根节点到叶子节点的路径,使路径上的节点值之和等于 targetSum。遍历过程中维护剩余目标值:访问当前节点时减去节点值,到达叶子节点时判断剩余值是否为 0。
易错点
路径必须终止于叶子节点,不能在中间节点处仅因为剩余值为 0 就返回
true。
class Solution {
private:
bool traversal(TreeNode* node, int remaining) {
remaining -= node->val;
if (node->left == nullptr && node->right == nullptr) {
return remaining == 0;
}
if (node->left != nullptr && traversal(node->left, remaining)) {
return true;
}
if (node->right != nullptr && traversal(node->right, remaining)) {
return true;
}
return false;
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
return traversal(root, targetSum);
}
};class Solution {
private:
bool traversal(TreeNode* node, int remaining) {
remaining -= node->val;
if (node->left == nullptr && node->right == nullptr) {
return remaining == 0;
}
if (node->left != nullptr && traversal(node->left, remaining)) {
return true;
}
if (node->right != nullptr && traversal(node->right, remaining)) {
return true;
}
return false;
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
return traversal(root, targetSum);
}
};remaining 按值传递,因此返回上一层时会自动恢复,无须手动执行加法回溯。
- 时间复杂度:
- 空间复杂度:,来自递归调用栈;最坏情况下为
十七、从中序与后序遍历序列构造二叉树
两种遍历序列分别具有以下结构:
- 中序遍历:
左子树 → 根节点 → 右子树 - 后序遍历:
左子树 → 右子树 → 根节点
因此,后序序列的最后一个元素就是当前子树的根节点。用它在中序序列中定位切割点,即可确定左右子树的范围,再递归构造。
递归步骤
- 从后序序列末尾取得当前根节点。
- 在中序序列中找到根节点的位置。
- 根节点左侧属于左子树,右侧属于右子树。
- 逆序读取后序序列时,顺序是“根 → 右 → 左”,因此必须先构造右子树,再构造左子树。
直接切割并复制数组容易理解,但最坏情况下会产生 的查找和复制开销。下面使用哈希表记录中序下标,并使用区间边界避免复制数组。
class Solution {
private:
unordered_map<int, int> inorderIndex;
int postorderIndex = 0;
TreeNode* build(
const vector<int>& postorder,
int inorderLeft,
int inorderRight
) {
if (inorderLeft > inorderRight) {
return nullptr;
}
int rootValue = postorder[postorderIndex--];
TreeNode* root = new TreeNode(rootValue);
int rootIndex = inorderIndex[rootValue];
root->right = build(postorder, rootIndex + 1, inorderRight);
root->left = build(postorder, inorderLeft, rootIndex - 1);
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.empty()) {
return nullptr;
}
for (int i = 0; i < static_cast<int>(inorder.size()); ++i) {
inorderIndex[inorder[i]] = i;
}
postorderIndex = static_cast<int>(postorder.size()) - 1;
return build(postorder, 0, static_cast<int>(inorder.size()) - 1);
}
};class Solution {
private:
unordered_map<int, int> inorderIndex;
int postorderIndex = 0;
TreeNode* build(
const vector<int>& postorder,
int inorderLeft,
int inorderRight
) {
if (inorderLeft > inorderRight) {
return nullptr;
}
int rootValue = postorder[postorderIndex--];
TreeNode* root = new TreeNode(rootValue);
int rootIndex = inorderIndex[rootValue];
root->right = build(postorder, rootIndex + 1, inorderRight);
root->left = build(postorder, inorderLeft, rootIndex - 1);
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.empty()) {
return nullptr;
}
for (int i = 0; i < static_cast<int>(inorder.size()); ++i) {
inorderIndex[inorder[i]] = i;
}
postorderIndex = static_cast<int>(postorder.size()) - 1;
return build(postorder, 0, static_cast<int>(inorder.size()) - 1);
}
};- 时间复杂度:
- 空间复杂度:,用于哈希表;递归调用栈额外占用
2026-09-09(周三)
二叉树(六)
十八、最大二叉树
题目:654. 最大二叉树
最大二叉树的构造规则如下:
- 找到当前区间中的最大值,将其作为根节点。
- 使用最大值左侧的区间递归构造左子树。
- 使用最大值右侧的区间递归构造右子树。
与从中序与后序遍历序列构造二叉树相同,可以通过区间下标切分数组,避免在每层递归中创建新的 vector。下面统一使用左闭右开区间 [left, right):
class Solution {
private:
TreeNode* build(const vector<int>& nums, int left, int right) {
if (left >= right) {
return nullptr;
}
int maxIndex = left;
for (int i = left + 1; i < right; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
TreeNode* root = new TreeNode(nums[maxIndex]);
root->left = build(nums, left, maxIndex);
root->right = build(nums, maxIndex + 1, right);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums, 0, static_cast<int>(nums.size()));
}
};class Solution {
private:
TreeNode* build(const vector<int>& nums, int left, int right) {
if (left >= right) {
return nullptr;
}
int maxIndex = left;
for (int i = left + 1; i < right; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
TreeNode* root = new TreeNode(nums[maxIndex]);
root->left = build(nums, left, maxIndex);
root->right = build(nums, maxIndex + 1, right);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums, 0, static_cast<int>(nums.size()));
}
};使用下标避免了数组复制,但每层仍需扫描区间寻找最大值:
- 时间复杂度:平均为 ,最坏情况下为
- 空间复杂度:,来自递归调用栈;最坏情况下为
进一步优化
如果需要将时间复杂度优化到 ,可以使用单调递减栈构造最大二叉树。
十九、合并二叉树
题目:617. 合并二叉树
同时遍历两棵树中位置相同的节点:
- 如果一棵树的当前节点为空,直接返回另一棵树的节点。
- 如果两个节点均存在,将它们的值相加。
- 递归合并左右子树,并将结果连接到第一棵树上。
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr) {
return root2;
}
if (root2 == nullptr) {
return root1;
}
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr) {
return root2;
}
if (root2 == nullptr) {
return root1;
}
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};原地修改
该写法会直接修改
root1,并可能复用root2中未重叠的子树。如果需要保留两棵原树,应为结果树创建新节点。
- 时间复杂度:,其中 为两棵树重叠部分的节点数
- 空间复杂度:,其中 为重叠部分的最大递归深度
二十、二叉搜索树中的搜索
二叉搜索树(BST)具有有序性:
- 左子树中的所有节点值均小于根节点值。
- 右子树中的所有节点值均大于根节点值。
- 左右子树也分别是二叉搜索树。
因此无须遍历整棵树:目标值较小时只搜索左子树,较大时只搜索右子树。节点的有序性已经确定了唯一的搜索方向,所以不需要遍历其他分支,也不需要回溯。
方法一:递归搜索
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int value) {
if (root == nullptr || root->val == value) {
return root;
}
if (value < root->val) {
return searchBST(root->left, value);
}
return searchBST(root->right, value);
}
};class Solution {
public:
TreeNode* searchBST(TreeNode* root, int value) {
if (root == nullptr || root->val == value) {
return root;
}
if (value < root->val) {
return searchBST(root->left, value);
}
return searchBST(root->right, value);
}
};方法二:迭代搜索
每次比较后直接移动到左孩子或右孩子,直到找到目标节点或走到空节点。
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int value) {
while (root != nullptr) {
if (value < root->val) {
root = root->left;
} else if (value > root->val) {
root = root->right;
} else {
return root;
}
}
return nullptr;
}
};class Solution {
public:
TreeNode* searchBST(TreeNode* root, int value) {
while (root != nullptr) {
if (value < root->val) {
root = root->left;
} else if (value > root->val) {
root = root->right;
} else {
return root;
}
}
return nullptr;
}
};- 时间复杂度:;平衡时为 ,最坏情况下为
- 空间复杂度:递归法为 ,迭代法为
2026-09-10(周四)
祝所有认真负责的教师节日快乐!
二叉树(七)
二十一、验证二叉搜索树
题目:98. 验证二叉搜索树
二叉搜索树的中序遍历结果应当是一个严格递增的序列。因此,验证二叉搜索树可以转化为判断中序序列是否严格递增。
易错点
有效二叉搜索树中不能出现相同值,所以只要发现
values[i] <= values[i - 1],就应返回false。
class Solution {
private:
void inorder(TreeNode* node, vector<int>& values) {
if (node == nullptr) {
return;
}
inorder(node->left, values);
values.push_back(node->val);
inorder(node->right, values);
}
public:
bool isValidBST(TreeNode* root) {
vector<int> values;
inorder(root, values);
for (size_t i = 1; i < values.size(); ++i) {
if (values[i] <= values[i - 1]) {
return false;
}
}
return true;
}
};class Solution {
private:
void inorder(TreeNode* node, vector<int>& values) {
if (node == nullptr) {
return;
}
inorder(node->left, values);
values.push_back(node->val);
inorder(node->right, values);
}
public:
bool isValidBST(TreeNode* root) {
vector<int> values;
inorder(root, values);
for (size_t i = 1; i < values.size(); ++i) {
if (values[i] <= values[i - 1]) {
return false;
}
}
return true;
}
};- 时间复杂度:
- 空间复杂度:,用于中序序列;递归调用栈额外占用
二十二、二叉搜索树的最小绝对差
二叉搜索树的中序序列严格递增,任意两节点之间的最小差值一定出现在序列中相邻的两个元素之间。因此,只需在中序遍历中比较相邻节点。
方法一:转换为有序数组
class Solution {
private:
void inorder(TreeNode* node, vector<int>& values) {
if (node == nullptr) {
return;
}
inorder(node->left, values);
values.push_back(node->val);
inorder(node->right, values);
}
public:
int getMinimumDifference(TreeNode* root) {
vector<int> values;
inorder(root, values);
int result = INT_MAX;
for (size_t i = 1; i < values.size(); ++i) {
result = min(result, values[i] - values[i - 1]);
}
return result;
}
};class Solution {
private:
void inorder(TreeNode* node, vector<int>& values) {
if (node == nullptr) {
return;
}
inorder(node->left, values);
values.push_back(node->val);
inorder(node->right, values);
}
public:
int getMinimumDifference(TreeNode* root) {
vector<int> values;
inorder(root, values);
int result = INT_MAX;
for (size_t i = 1; i < values.size(); ++i) {
result = min(result, values[i] - values[i - 1]);
}
return result;
}
};- 时间复杂度:
- 空间复杂度:,用于保存中序序列
方法二:记录前驱节点
无须保存完整序列,只需使用 previous 记录中序遍历中的前一个节点。
class Solution {
private:
int result = INT_MAX;
TreeNode* previous = nullptr;
void inorder(TreeNode* node) {
if (node == nullptr) {
return;
}
inorder(node->left);
if (previous != nullptr) {
result = min(result, node->val - previous->val);
}
previous = node;
inorder(node->right);
}
public:
int getMinimumDifference(TreeNode* root) {
result = INT_MAX;
previous = nullptr;
inorder(root);
return result;
}
};class Solution {
private:
int result = INT_MAX;
TreeNode* previous = nullptr;
void inorder(TreeNode* node) {
if (node == nullptr) {
return;
}
inorder(node->left);
if (previous != nullptr) {
result = min(result, node->val - previous->val);
}
previous = node;
inorder(node->right);
}
public:
int getMinimumDifference(TreeNode* root) {
result = INT_MAX;
previous = nullptr;
inorder(root);
return result;
}
};- 时间复杂度:
- 空间复杂度:,仅计算递归调用栈;最坏情况下为
二十三、二叉搜索树中的众数
众数是出现频率最高的元素。如果是普通二叉树,可以使用哈希表统计频率;对于二叉搜索树,中序遍历会使相同值连续出现,因此可以直接统计连续元素的出现次数。
需要维护四个状态:
previous:中序遍历中的前一个节点。currentCount:当前值连续出现的次数。maxCount:已经发现的最大出现次数。result:所有出现次数等于maxCount的节点值。
class Solution {
private:
int currentCount = 0;
int maxCount = 0;
TreeNode* previous = nullptr;
vector<int> result;
void inorder(TreeNode* node) {
if (node == nullptr) {
return;
}
inorder(node->left);
if (previous != nullptr && previous->val == node->val) {
++currentCount;
} else {
currentCount = 1;
}
previous = node;
if (currentCount > maxCount) {
maxCount = currentCount;
result.clear();
result.push_back(node->val);
} else if (currentCount == maxCount) {
result.push_back(node->val);
}
inorder(node->right);
}
public:
vector<int> findMode(TreeNode* root) {
currentCount = 0;
maxCount = 0;
previous = nullptr;
result.clear();
inorder(root);
return result;
}
};class Solution {
private:
int currentCount = 0;
int maxCount = 0;
TreeNode* previous = nullptr;
vector<int> result;
void inorder(TreeNode* node) {
if (node == nullptr) {
return;
}
inorder(node->left);
if (previous != nullptr && previous->val == node->val) {
++currentCount;
} else {
currentCount = 1;
}
previous = node;
if (currentCount > maxCount) {
maxCount = currentCount;
result.clear();
result.push_back(node->val);
} else if (currentCount == maxCount) {
result.push_back(node->val);
}
inorder(node->right);
}
public:
vector<int> findMode(TreeNode* root) {
currentCount = 0;
maxCount = 0;
previous = nullptr;
result.clear();
inorder(root);
return result;
}
};- 时间复杂度:
- 空间复杂度:不计结果数组为 ,来自递归调用栈
2026-09-11(周五)
二叉树(八)
二十四、二叉树的最近公共祖先
最近公共祖先是同时包含节点 p 和 q 的祖先中深度最大的节点;节点本身也可以是自己的祖先。
普通二叉树没有有序性,因此需要使用后序遍历自底向上收集结果:
- 当前节点为空,或等于
p、q时,直接返回当前节点。 - 左右子树均返回非空节点时,说明
p和q分布在当前节点两侧,当前节点就是最近公共祖先。 - 只有一侧返回非空节点时,将该结果继续向上传递。
- 两侧均为空时,返回
nullptr。
class Solution {
public:
TreeNode* lowestCommonAncestor(
TreeNode* root,
TreeNode* p,
TreeNode* q
) {
if (root == nullptr || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) {
return root;
}
return left != nullptr ? left : right;
}
};class Solution {
public:
TreeNode* lowestCommonAncestor(
TreeNode* root,
TreeNode* p,
TreeNode* q
) {
if (root == nullptr || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) {
return root;
}
return left != nullptr ? left : right;
}
};示例
查找节点 6 和 5 时,左右子树分别向节点 7 返回结果,因此节点 7 是最近公共祖先。
- 时间复杂度:
- 空间复杂度:,来自递归调用栈;最坏情况下为
二十五、二叉搜索树的最近公共祖先
二叉搜索树具有有序性,可以从根节点向下直接确定搜索方向:
- 当前值同时大于
p和q的值:最近公共祖先位于左子树。 - 当前值同时小于
p和q的值:最近公共祖先位于右子树。 - 当前值位于二者值域之间,或等于其中一个节点:当前节点就是最近公共祖先。
这里的“值域之间”与 p、q 的大小顺序无关,判断两者是否位于当前节点同一侧即可。
class Solution {
public:
TreeNode* lowestCommonAncestor(
TreeNode* root,
TreeNode* p,
TreeNode* q
) {
if (root == nullptr) {
return nullptr;
}
if (root->val > p->val && root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
}
if (root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};class Solution {
public:
TreeNode* lowestCommonAncestor(
TreeNode* root,
TreeNode* p,
TreeNode* q
) {
if (root == nullptr) {
return nullptr;
}
if (root->val > p->val && root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
}
if (root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};- 时间复杂度:;平衡时为 ,最坏情况下为
- 空间复杂度:,来自递归调用栈
二十六、二叉搜索树中的插入操作
利用二叉搜索树的有序性向下查找:插入值较小时进入左子树,较大时进入右子树;遇到空位置后创建新节点并连接到父节点即可。
方法一:递归插入
递归函数返回当前子树的根节点,使新节点能够通过返回值连接到原树中。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int value) {
if (root == nullptr) {
return new TreeNode(value);
}
if (value < root->val) {
root->left = insertIntoBST(root->left, value);
} else {
root->right = insertIntoBST(root->right, value);
}
return root;
}
};class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int value) {
if (root == nullptr) {
return new TreeNode(value);
}
if (value < root->val) {
root->left = insertIntoBST(root->left, value);
} else {
root->right = insertIntoBST(root->right, value);
}
return root;
}
};方法二:迭代插入
迭代时必须保存 parent。当 current 走到空位置后,需要通过父节点完成新节点的连接。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int value) {
if (root == nullptr) {
return new TreeNode(value);
}
TreeNode* current = root;
TreeNode* parent = nullptr;
while (current != nullptr) {
parent = current;
if (value < current->val) {
current = current->left;
} else {
current = current->right;
}
}
if (value < parent->val) {
parent->left = new TreeNode(value);
} else {
parent->right = new TreeNode(value);
}
return root;
}
};class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int value) {
if (root == nullptr) {
return new TreeNode(value);
}
TreeNode* current = root;
TreeNode* parent = nullptr;
while (current != nullptr) {
parent = current;
if (value < current->val) {
current = current->left;
} else {
current = current->right;
}
}
if (value < parent->val) {
parent->left = new TreeNode(value);
} else {
parent->right = new TreeNode(value);
}
return root;
}
};- 时间复杂度:;平衡时为 ,最坏情况下为
- 空间复杂度:递归法为 ,迭代法为
2026-09-12(周六)
二叉树(九)
二十七、删除二叉搜索树中的节点
先利用二叉搜索树的有序性定位目标节点,再根据孩子数量调整结构:
- 没有找到目标:遍历到空节点,直接返回
nullptr。 - 目标是叶子节点:删除后返回
nullptr。 - 目标只有右孩子:删除目标,让右孩子补位。
- 目标只有左孩子:删除目标,让左孩子补位。
- 目标有两个孩子:找到右子树最左侧节点,将原左子树连接到它的左侧,再让原右孩子补位。
代码中“叶子节点”可以合并到“左孩子为空”的分支,因为此时右孩子也可能是 nullptr。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) {
return nullptr;
}
if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
}
if (key > root->val) {
root->right = deleteNode(root->right, key);
return root;
}
if (root->left == nullptr) {
TreeNode* newRoot = root->right;
delete root;
return newRoot;
}
if (root->right == nullptr) {
TreeNode* newRoot = root->left;
delete root;
return newRoot;
}
TreeNode* successor = root->right;
while (successor->left != nullptr) {
successor = successor->left;
}
successor->left = root->left;
TreeNode* newRoot = root->right;
delete root;
return newRoot;
}
};class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) {
return nullptr;
}
if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
}
if (key > root->val) {
root->right = deleteNode(root->right, key);
return root;
}
if (root->left == nullptr) {
TreeNode* newRoot = root->right;
delete root;
return newRoot;
}
if (root->right == nullptr) {
TreeNode* newRoot = root->left;
delete root;
return newRoot;
}
TreeNode* successor = root->right;
while (successor->left != nullptr) {
successor = successor->left;
}
successor->left = root->left;
TreeNode* newRoot = root->right;
delete root;
return newRoot;
}
};返回值的作用
递归函数返回删除后子树的新根节点,父节点必须重新接收该指针,否则删除根节点或孩子补位后,树的连接关系会丢失。
- 时间复杂度:;平衡时为 ,最坏情况下为
- 空间复杂度:,来自递归调用栈
二十八、修剪二叉搜索树
题目:669. 修剪二叉搜索树
目标是只保留值位于闭区间 [low, high] 内的节点。利用二叉搜索树的有序性,可以直接舍弃整侧子树:
root->val < low:左子树中的值全部更小,只需继续修剪右子树。root->val > high:右子树中的值全部更大,只需继续修剪左子树。- 当前值在区间内:分别修剪左右子树,并重新连接返回结果。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) {
return nullptr;
}
if (root->val < low) {
return trimBST(root->right, low, high);
}
if (root->val > high) {
return trimBST(root->left, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) {
return nullptr;
}
if (root->val < low) {
return trimBST(root->right, low, high);
}
if (root->val > high) {
return trimBST(root->left, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};- 时间复杂度:最坏为
- 空间复杂度:,来自递归调用栈;最坏情况下为
二十九、将有序数组转换为二叉搜索树
有序数组的中间元素可以作为当前根节点:左侧区间递归构造左子树,右侧区间递归构造右子树。持续选择中点能够使左右子树规模尽量接近,从而得到高度平衡的二叉搜索树。
下面统一使用左闭右开区间 [left, right):
class Solution {
private:
TreeNode* build(const vector<int>& nums, int left, int right) {
if (left >= right) {
return nullptr;
}
int middle = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[middle]);
root->left = build(nums, left, middle);
root->right = build(nums, middle + 1, right);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return build(nums, 0, static_cast<int>(nums.size()));
}
};class Solution {
private:
TreeNode* build(const vector<int>& nums, int left, int right) {
if (left >= right) {
return nullptr;
}
int middle = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[middle]);
root->left = build(nums, left, middle);
root->right = build(nums, middle + 1, right);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return build(nums, 0, static_cast<int>(nums.size()));
}
};- 时间复杂度:
- 空间复杂度:,来自平衡树的递归调用栈;不计结果树本身
三十、把二叉搜索树转换为累加树
普通中序遍历“左 → 中 → 右”会得到升序序列。为了从大到小累加节点值,应使用反中序遍历“右 → 中 → 左”:
- 先处理值更大的右子树。
- 将当前节点值加入累计和,并用累计和更新当前节点。
- 最后处理值更小的左子树。
class Solution {
private:
int runningSum = 0;
void convert(TreeNode* node) {
if (node == nullptr) {
return;
}
convert(node->right);
runningSum += node->val;
node->val = runningSum;
convert(node->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
runningSum = 0;
convert(root);
return root;
}
};class Solution {
private:
int runningSum = 0;
void convert(TreeNode* node) {
if (node == nullptr) {
return;
}
convert(node->right);
runningSum += node->val;
node->val = runningSum;
convert(node->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
runningSum = 0;
convert(root);
return root;
}
};- 时间复杂度:
- 空间复杂度:,来自递归调用栈;最坏情况下为
三十一、二叉树总结
二叉树题目的关键,是先判断信息应该自顶向下传递,还是自底向上汇总,以及能否利用二叉搜索树的有序性剪枝。
| 问题类型 | 常用方法 | 核心原因 |
|---|---|---|
| 构造或先处理当前节点 | 前序遍历、分治 | 先确定根节点,再构造或处理左右子树 |
| 高度、平衡、公共祖先等子树属性 | 后序遍历 | 先获得左右子树结果,再计算当前节点 |
| 根到叶路径、深度记录 | 前序遍历与回溯 | 自顶向下维护路径或状态 |
| 按层处理节点 | 层序遍历(BFS) | 队列能够划分不同层级 |
| BST 的排序、差值、频率问题 | 中序或反中序遍历 | 充分利用有序序列性质 |
| BST 的搜索、插入、删除和修剪 | 比较节点值并剪枝 | 每次只需进入可能包含答案的一侧 |
选择遍历方式
- 构造类问题:通常先创建当前根节点,再递归构造子树。
- 普通二叉树属性问题:若依赖左右子树返回值,优先考虑后序遍历。
- 路径类问题:优先考虑前序遍历,并判断是否需要回溯。
- 二叉搜索树问题:先思考能否利用中序有序性或大小关系剪枝。
2026-09-15(周二)
回溯算法(一)
一、回溯算法理论基础
回溯通常与递归相伴:递归进入下一层负责继续尝试,递归返回上一层则完成状态撤销。回溯法本质上是穷举,因此通常不是高效算法,但可以通过剪枝减少无效搜索。
回溯算法常用于解决以下问题:
- 组合问题:从 个数中按规则选出 个数的集合。
- 切割问题:按照一定规则切割字符串。
- 子集问题:找出集合中满足条件的所有子集。
- 排列问题:按照一定规则生成全排列。
- 棋盘问题:例如 N 皇后、解数独等。
回溯问题通常可以抽象成一棵树:
- 集合的大小决定搜索树的宽度。
- 递归的深度决定搜索树的深度。
for循环负责横向遍历当前层的候选项。backtracking递归负责纵向进入下一层。
二、组合
题目:77. 组合
每次从集合中选择一个元素后,下一层可选择的范围都要相应收缩。对于 中选取 个数的问题, 决定搜索树的宽度, 决定搜索树的深度;当路径长度达到 时,就找到了一组答案。
使用 startIndex 记录下一层搜索的起始位置,可以避免重复选择以及产生不同顺序的相同组合。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for (int i = startIndex; i <= n; i++) {
path.push_back(i);
backtracking(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
result.clear();
path.clear();
backtracking(n, k, 1);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for (int i = startIndex; i <= n; i++) {
path.push_back(i);
backtracking(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
result.clear();
path.clear();
backtracking(n, k, 1);
return result;
}
};- 时间复杂度:,复制每个组合需要 时间
- 空间复杂度:,不计结果数组
三、组合剪枝优化
回溯虽然属于暴力搜索,但可以调整每层 for 循环的结束位置进行剪枝:如果从当前位置开始,剩余元素数量已经不足以补齐组合,就没有必要继续搜索。
设当前准备选择元素 i:
- 已选择的元素个数为
path.size()。 - 还需要选择
k - path.size()个元素。 - 从
i到n共有n - i + 1个元素。
要保证剩余元素足够,需要满足:
整理后得到循环上界:
其中 +1 是因为区间包含起始位置 i。例如 、,且当前尚未选择元素时,第一层最多从 开始;如果从 开始,剩余元素已经不足三个。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for (int i = startIndex;
i <= n - (k - static_cast<int>(path.size())) + 1;
i++) {
path.push_back(i);
backtracking(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
result.clear();
path.clear();
backtracking(n, k, 1);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for (int i = startIndex;
i <= n - (k - static_cast<int>(path.size())) + 1;
i++) {
path.push_back(i);
backtracking(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
result.clear();
path.clear();
backtracking(n, k, 1);
return result;
}
};- 时间复杂度:,剪枝减少了无效分支,但渐进上界不变
- 空间复杂度:,不计结果数组
2026-09-16(周三)
回溯算法(二)
四、组合总和 III
从数字 1 到 9 中选择 k 个互不重复的数字,使其总和等于 n。本题在普通组合的基础上增加了目标和限制。
可以同时进行两类剪枝:
- 数量剪枝:剩余数字不足以填满
k个位置时停止枚举。 - 总和剪枝:候选数字已经大于剩余目标值时,后续更大的数字也不可能满足条件。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int k, int remaining, int startIndex) {
if (static_cast<int>(path.size()) == k) {
if (remaining == 0) {
result.push_back(path);
}
return;
}
int needed = k - static_cast<int>(path.size());
int maxStart = 9 - needed + 1;
for (int number = startIndex; number <= maxStart; ++number) {
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(k, remaining - number, number + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
result.clear();
path.clear();
backtracking(k, n, 1);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int k, int remaining, int startIndex) {
if (static_cast<int>(path.size()) == k) {
if (remaining == 0) {
result.push_back(path);
}
return;
}
int needed = k - static_cast<int>(path.size());
int maxStart = 9 - needed + 1;
for (int number = startIndex; number <= maxStart; ++number) {
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(k, remaining - number, number + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
result.clear();
path.clear();
backtracking(k, n, 1);
return result;
}
};- 时间复杂度:上界为 ;实际搜索分支会因剪枝而减少
- 空间复杂度:不计结果集为
五、电话号码的字母组合
每一层递归处理一个数字,当前数字对应的字母就是该层的所有选择。递归深度等于数字字符串长度,因此不需要根据输入长度手写多层 for 循环。
题目输入只包含 2 到 9;映射表中仍为 0 和 1 保留空字符串,便于通过下标直接访问。
class Solution {
private:
const vector<string> letterMap = {
"", "", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz"
};
vector<string> result;
string path;
void backtracking(const string& digits, int index) {
if (index == static_cast<int>(digits.size())) {
result.push_back(path);
return;
}
int digit = digits[index] - '0';
for (char letter : letterMap[digit]) {
path.push_back(letter);
backtracking(digits, index + 1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
result.clear();
path.clear();
if (digits.empty()) {
return result;
}
backtracking(digits, 0);
return result;
}
};class Solution {
private:
const vector<string> letterMap = {
"", "", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz"
};
vector<string> result;
string path;
void backtracking(const string& digits, int index) {
if (index == static_cast<int>(digits.size())) {
result.push_back(path);
return;
}
int digit = digits[index] - '0';
for (char letter : letterMap[digit]) {
path.push_back(letter);
backtracking(digits, index + 1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
result.clear();
path.clear();
if (digits.empty()) {
return result;
}
backtracking(digits, 0);
return result;
}
};- 时间复杂度:,其中 为数字个数,、 分别是映射 3 个和 4 个字母的数字数量
- 空间复杂度:不计结果集为
六、组合总和
题目:39. 组合总和
候选数组中的每个数字可以被重复选择。与前面的组合题不同,递归进入下一层时仍传入当前下标 index,而不是 index + 1。
先对数组排序后,如果当前候选值已经大于剩余目标值,后续数字只会更大,因此可以直接结束当前层循环。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& candidates,
int remaining,
int startIndex
) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int index = startIndex;
index < static_cast<int>(candidates.size());
++index) {
int number = candidates[index];
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(candidates, remaining - number, index);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(
vector<int>& candidates,
int target
) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& candidates,
int remaining,
int startIndex
) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int index = startIndex;
index < static_cast<int>(candidates.size());
++index) {
int number = candidates[index];
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(candidates, remaining - number, index);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(
vector<int>& candidates,
int target
) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};
startIndex的区别
- 元素只能使用一次:递归传入
index + 1。- 元素可以重复使用:递归传入
index。- 组合问题始终从
startIndex向后搜索,以避免出现顺序不同但内容相同的重复组合。
- 时间复杂度:与候选值和目标值有关,最坏情况下呈指数级
- 空间复杂度:不计结果集,递归深度最多约为
2026-09-17(周四)
回溯算法(三)
七、组合总和 II
题目:40. 组合总和 II
本题与组合总和的关键区别如下:
| 对比项 | 组合总和 | 组合总和 II |
|---|---|---|
| 候选数组 | 元素互不相同 | 可能包含重复元素 |
| 单个位置的使用次数 | 可以重复使用 | 最多使用一次 |
| 下一层起点 | index | index + 1 |
| 是否需要树层去重 | 不需要 | 需要 |
难点在于:候选数组可以包含相同数值,但结果集中不能出现重复组合。应当区分两种情况:
- 同一树层:相同数值会生成相同组合,需要跳过。
- 同一树枝:不同位置上的相同数值可以同时进入一个组合,例如
[1, 1, 6],不能跳过。
数组排序后,相同元素会彼此相邻。条件 index > startIndex 表示当前元素不是本层的第一个选择,因此可以用下面的判断完成树层去重:
if (index > startIndex
&& candidates[index] == candidates[index - 1]) {
continue;
}if (index > startIndex
&& candidates[index] == candidates[index - 1]) {
continue;
}这与 used[index - 1] == false 判断同一树层的思路等价,但使用 startIndex 更简洁。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& candidates,
int remaining,
int startIndex
) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int index = startIndex;
index < static_cast<int>(candidates.size());
++index) {
if (index > startIndex
&& candidates[index] == candidates[index - 1]) {
continue;
}
int number = candidates[index];
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(candidates, remaining - number, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(
vector<int>& candidates,
int target
) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& candidates,
int remaining,
int startIndex
) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int index = startIndex;
index < static_cast<int>(candidates.size());
++index) {
if (index > startIndex
&& candidates[index] == candidates[index - 1]) {
continue;
}
int number = candidates[index];
if (number > remaining) {
break;
}
path.push_back(number);
backtracking(candidates, remaining - number, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(
vector<int>& candidates,
int target
) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0);
return result;
}
};- 时间复杂度:最坏约为 ,另有排序开销
- 空间复杂度:不计结果集为 ,用于递归调用栈和当前路径
Git 学习
Git 核心模型
将 Git 理解成“提交组成的链表”有助于入门,但更准确地说,Git 的提交历史是一张有向无环图(DAG):普通提交通常有一个父提交,合并提交可以有多个父提交。
A ── B ── C ← main
└── D ── E ← featureA ── B ── C ← main
└── D ── E ← featureGit 的关键对象与指针:
- Blob:保存文件内容。
- Tree:保存目录结构,并指向 Blob 或其他 Tree。
- Commit:指向项目快照对应的 Tree,同时记录父提交、作者、时间和提交信息。
- Branch:指向某个提交的可移动引用;新提交产生后,当前分支会向前移动。
- Tag:通常作为指向特定提交的固定标记。
- HEAD:表示当前检出的分支或提交。
- Index / Staging Area:暂存区,即下一次提交快照的候选内容。
由于提交内容包含父提交的哈希,修改历史中的旧提交并不是“原地修改”,而是创建新的提交;其后代提交也需要重新创建,因此 rebase 等操作会改变提交 ID。
Git 常用命令
仓库、暂存与提交
| 命令 | 作用 |
|---|---|
git init | 在当前目录初始化仓库,并创建 .git 目录 |
git status | 查看工作区、暂存区和当前分支状态 |
git add <file> | 将指定文件的当前内容加入暂存区 |
git restore --staged <file> | 取消暂存,但保留工作区修改 |
git reset <file> | 传统的取消暂存写法;默认不会删除工作区修改 |
git commit -m "message" | 使用暂存区内容创建新提交 |
git log --oneline --graph --decorate --all | 以图形化精简形式查看全部分支历史 |
分支、合并与并行工作区
| 命令 | 作用 |
|---|---|
git branch | 列出本地分支 |
git branch <name> | 创建分支,但不切换 |
git switch <name> | 切换到已有分支 |
git switch -c <name> | 创建并切换分支;旧式等价写法为 git checkout -b <name> |
git checkout <revision> | 检出指定提交;检出提交哈希时通常进入 detached HEAD 状态 |
git merge <branch> | 将指定分支合并进当前分支 |
git rebase <base> | 将当前分支上的提交重新应用到新的基点上 |
git worktree add <path> <branch> | 在另一个目录同时检出并处理指定分支 |
撤销与忽略
| 命令 | 作用 |
|---|---|
git restore <file> | 丢弃指定文件尚未暂存的修改 |
git revert <commit> | 创建一个新提交,反向抵消指定提交的修改 |
.gitignore | 声明不希望 Git 跟踪的文件匹配规则 |
使用提醒
.gitignore只影响尚未被跟踪的文件;已跟踪文件需先使用git rm --cached <file>从暂存索引移除。git reset --hard和git restore <file>可能永久丢弃本地修改,执行前应先确认或备份。git rebase会重写提交历史,避免随意对已经共享的公共分支执行。
2026-09-18(周五)
九一八事变纪念日
默哀。
回溯算法(四)
八、分割回文串
题目:131. 分割回文串
切割问题可以转换为组合问题:每一层递归决定当前子串的结束位置,切下合法子串后,再从剩余字符串的起点继续切割。
以字符串 abcdef 为例:先切出 a,再到 bcdef 中寻找第二段;如果第二段切出 b,则继续到 cdef 中寻找第三段。由此形成一棵回溯搜索树。
关键点:
startIndex表示本轮待切割子串的起始位置。end枚举当前子串的结束位置,区间为[startIndex, end]。- 只有当前子串是回文串时,才能加入路径并递归处理剩余部分。
- 当
startIndex == s.size()时,切割线已经到达字符串末尾,得到一种完整方案。
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
bool isPalindrome(const string& s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
}
++start;
--end;
}
return true;
}
void backtracking(const string& s, int startIndex) {
if (startIndex == static_cast<int>(s.size())) {
result.push_back(path);
return;
}
for (int end = startIndex;
end < static_cast<int>(s.size());
++end) {
if (!isPalindrome(s, startIndex, end)) {
continue;
}
path.push_back(s.substr(startIndex, end - startIndex + 1));
backtracking(s, end + 1);
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s, 0);
return result;
}
};class Solution {
private:
vector<vector<string>> result;
vector<string> path;
bool isPalindrome(const string& s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
}
++start;
--end;
}
return true;
}
void backtracking(const string& s, int startIndex) {
if (startIndex == static_cast<int>(s.size())) {
result.push_back(path);
return;
}
for (int end = startIndex;
end < static_cast<int>(s.size());
++end) {
if (!isPalindrome(s, startIndex, end)) {
continue;
}
path.push_back(s.substr(startIndex, end - startIndex + 1));
backtracking(s, end + 1);
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s, 0);
return result;
}
};- 时间复杂度:最坏约为 ,需要枚举切割方案并判断、复制子串
- 空间复杂度:不计结果集为 ,用于递归调用栈和当前切割路径
九、复原 IP 地址
题目:93. 复原 IP 地址
这也是切割问题:在字符串中放置三个点号,将其划分成四段,并通过回溯枚举所有可能的切割位置。
IPv4 每一段必须满足:
- 内容只能包含数字,且不能为空。
- 数值范围为 。
- 除数字
0本身外,不能以0开头。
搜索过程仍符合回溯算法通用模板:确定当前段的结束位置,验证该段,递归切割下一段,最后撤销点号。
class Solution {
private:
vector<string> result;
bool isValid(const string& s, int start, int end) {
if (start > end) {
return false;
}
if (s[start] == '0' && start != end) {
return false;
}
int number = 0;
for (int index = start; index <= end; ++index) {
if (s[index] < '0' || s[index] > '9') {
return false;
}
number = number * 10 + (s[index] - '0');
if (number > 255) {
return false;
}
}
return true;
}
void backtracking(string& s, int startIndex, int pointCount) {
// 已放置三个点号,只需检查最后一段。
if (pointCount == 3) {
if (isValid(
s,
startIndex,
static_cast<int>(s.size()) - 1
)) {
result.push_back(s);
}
return;
}
for (int end = startIndex;
end < static_cast<int>(s.size());
++end) {
if (!isValid(s, startIndex, end)) {
// 当前段继续变长也不会重新合法,可以直接剪枝。
break;
}
s.insert(s.begin() + end + 1, '.');
backtracking(s, end + 2, pointCount + 1);
s.erase(s.begin() + end + 1);
}
}
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
// 四段地址,每段至少一位、至多三位。
if (s.size() < 4 || s.size() > 12) {
return result;
}
backtracking(s, 0, 0);
return result;
}
};class Solution {
private:
vector<string> result;
bool isValid(const string& s, int start, int end) {
if (start > end) {
return false;
}
if (s[start] == '0' && start != end) {
return false;
}
int number = 0;
for (int index = start; index <= end; ++index) {
if (s[index] < '0' || s[index] > '9') {
return false;
}
number = number * 10 + (s[index] - '0');
if (number > 255) {
return false;
}
}
return true;
}
void backtracking(string& s, int startIndex, int pointCount) {
// 已放置三个点号,只需检查最后一段。
if (pointCount == 3) {
if (isValid(
s,
startIndex,
static_cast<int>(s.size()) - 1
)) {
result.push_back(s);
}
return;
}
for (int end = startIndex;
end < static_cast<int>(s.size());
++end) {
if (!isValid(s, startIndex, end)) {
// 当前段继续变长也不会重新合法,可以直接剪枝。
break;
}
s.insert(s.begin() + end + 1, '.');
backtracking(s, end + 2, pointCount + 1);
s.erase(s.begin() + end + 1);
}
}
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
// 四段地址,每段至少一位、至多三位。
if (s.size() < 4 || s.size() > 12) {
return result;
}
backtracking(s, 0, 0);
return result;
}
};剪枝思路
- 输入长度小于
4或大于12时,不可能组成合法 IPv4 地址。- 每段最多三位;出现前导零或数值超过
255后,无须继续扩大当前区间。- 放置三个点号后立即验证最后一段,不再继续递归。
- 搜索规模:前三段各自最多尝试三种长度,切割位置的组合数量有限
- 空间复杂度:递归深度最多为 ;代码直接在原字符串中插入和删除点号
2026-09-20(周日)
回溯算法(五)
三类问题的结果收集位置不同:
| 问题类型 | 收集位置 | 原因 |
|---|---|---|
| 组合、切割 | 通常收集满足终止条件的节点 | 只有完整路径才是合法答案 |
| 子集 | 收集搜索树上的每个节点 | 每条路径本身都是一个子集 |
| 递增子序列 | 收集长度至少为 2 的节点 | 合法路径是答案,但还要继续向下搜索 |
十、子集
题目:78. 子集
组合问题和切割问题通常收集搜索树的叶子节点,而子集问题需要收集搜索树的所有节点。因此,每次进入递归函数时都要先保存当前路径,其中也包括空集。
循环自然会在 startIndex == nums.size() 时结束,所以可以省略单独的终止条件。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
// 搜索树上的每个节点都对应一个子集。
result.push_back(path);
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
path.push_back(nums[index]);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
// 搜索树上的每个节点都对应一个子集。
result.push_back(path);
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
path.push_back(nums[index]);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};- 时间复杂度:,共有 个子集,复制每个子集最多需要
- 空间复杂度:不计结果集为 ,用于递归调用栈和当前路径
十一、子集 II
题目:90. 子集 II
输入数组可能包含重复元素,但结果集中不能出现重复子集。处理方法与组合总和 II相同:
- 先排序,使相同元素相邻。
- 同一树枝可以选择不同位置上的相同元素。
- 同一树层中,相同数值只能作为一次起点。
因为 startIndex 已经标记了当前树层,所以可以直接使用 index > startIndex 判断同层重复,不必额外维护 used 数组。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
result.push_back(path);
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
if (index > startIndex && nums[index] == nums[index - 1]) {
continue;
}
path.push_back(nums[index]);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
result.push_back(path);
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
if (index > startIndex && nums[index] == nums[index - 1]) {
continue;
}
path.push_back(nums[index]);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return result;
}
};- 时间复杂度:排序需要 ,搜索与结果复制最坏为
- 空间复杂度:不计结果集为
十二、递增子序列
题目:491. 非递减子序列
目标是找出所有长度至少为 2 的非递减子序列。当前路径满足长度要求时就要加入结果,但不能立即返回,因为继续向下搜索可能得到更长的合法子序列。
本题同样需要对同一树层去重,但不能先对原数组排序,否则会破坏子序列的原始顺序。因此,要在每一层使用一个局部哈希集合,记录该父节点下已经选择过的数值。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
if (path.size() >= 2) {
result.push_back(path);
// 仍需继续搜索更长的非递减子序列。
}
unordered_set<int> usedOnLevel;
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
int number = nums[index];
bool decreases = !path.empty() && number < path.back();
bool duplicated = usedOnLevel.find(number) != usedOnLevel.end();
if (decreases || duplicated) {
continue;
}
usedOnLevel.insert(number);
path.push_back(number);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(const vector<int>& nums, int startIndex) {
if (path.size() >= 2) {
result.push_back(path);
// 仍需继续搜索更长的非递减子序列。
}
unordered_set<int> usedOnLevel;
for (int index = startIndex;
index < static_cast<int>(nums.size());
++index) {
int number = nums[index];
bool decreases = !path.empty() && number < path.back();
bool duplicated = usedOnLevel.find(number) != usedOnLevel.end();
if (decreases || duplicated) {
continue;
}
usedOnLevel.insert(number);
path.push_back(number);
backtracking(nums, index + 1);
path.pop_back();
}
}
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};两种树层去重方式
- 允许排序:排序后使用
index > startIndex && nums[index] == nums[index - 1]。- 不能排序:为每一层建立局部集合,记录该层已经使用过的数值。
- 时间复杂度:最坏约为 ,结果数量本身可能达到指数级
- 空间复杂度:不计结果集,递归路径为 ;各层局部集合同时存在时最坏可达
2026-09-21(周一)
回溯算法(六)
十三、全排列
题目:46. 全排列
排列是有顺序的,[1, 2] 和 [2, 1] 是两个不同结果。这与组合、子集问题的主要区别是:
| 对比项 | 组合、子集 | 排列 |
|---|---|---|
| 是否考虑顺序 | 否 | 是 |
| 每层搜索起点 | 从 startIndex 开始 | 每次都从下标 0 开始 |
| 防止元素重复使用 | 依靠下标向后推进 | 使用 used 数组记录当前路径 |
当路径长度等于数组长度时,说明所有元素都已经使用,得到一个完整排列。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& nums,
vector<bool>& used
) {
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for (int index = 0;
index < static_cast<int>(nums.size());
++index) {
if (used[index]) {
continue;
}
used[index] = true;
path.push_back(nums[index]);
backtracking(nums, used);
path.pop_back();
used[index] = false;
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
result.clear();
path.clear();
vector<bool> used(nums.size(), false);
backtracking(nums, used);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& nums,
vector<bool>& used
) {
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for (int index = 0;
index < static_cast<int>(nums.size());
++index) {
if (used[index]) {
continue;
}
used[index] = true;
path.push_back(nums[index]);
backtracking(nums, used);
path.pop_back();
used[index] = false;
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
result.clear();
path.clear();
vector<bool> used(nums.size(), false);
backtracking(nums, used);
return result;
}
};- 时间复杂度:,共有 个排列,复制每个结果需要
- 空间复杂度:不计结果集为 ,用于递归调用栈、路径和
used数组
十四、全排列 II
题目:47. 全排列 II
输入数组可能包含重复元素,但结果中不能出现重复排列。需要先排序,使相同元素相邻,再同时处理两种情况:
used[index] == true:当前元素已经出现在本条路径中,不能再次使用。nums[index] == nums[index - 1] && used[index - 1] == false:前一个相同元素没有出现在当前路径中,说明它已经在同一树层被使用,需要跳过当前元素。
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& nums,
vector<bool>& used
) {
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for (int index = 0;
index < static_cast<int>(nums.size());
++index) {
if (used[index]) {
continue;
}
// 同一树层中,相同数值只能作为一次选择。
if (index > 0 &&
nums[index] == nums[index - 1] &&
!used[index - 1]) {
continue;
}
used[index] = true;
path.push_back(nums[index]);
backtracking(nums, used);
path.pop_back();
used[index] = false;
}
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(), false);
backtracking(nums, used);
return result;
}
};class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(
const vector<int>& nums,
vector<bool>& used
) {
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for (int index = 0;
index < static_cast<int>(nums.size());
++index) {
if (used[index]) {
continue;
}
// 同一树层中,相同数值只能作为一次选择。
if (index > 0 &&
nums[index] == nums[index - 1] &&
!used[index - 1]) {
continue;
}
used[index] = true;
path.push_back(nums[index]);
backtracking(nums, used);
path.pop_back();
used[index] = false;
}
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(), false);
backtracking(nums, used);
return result;
}
};排列问题中的树层去重
排列每层都从下标
0开始,不能像组合问题一样使用index > startIndex。此时要结合排序后的相邻元素和used[index - 1],区分“同一树层”与“同一树枝”。
- 时间复杂度:排序为 ,搜索最坏为
- 空间复杂度:不计结果集为
十五、N 皇后
题目:51. N 皇后
皇后之间必须满足:
- 不能位于同一行。
- 不能位于同一列。
- 不能位于同一条斜线上。
递归的每一层只处理棋盘的一行,因此天然保证不会同行。随后枚举当前行的所有列,并检查正上方、左上方和右上方是否已有皇后。因为下方各行还未处理,无须向下检查。
class Solution {
private:
vector<vector<string>> result;
bool isValid(
int row,
int col,
const vector<string>& chessboard,
int boardSize
) {
// 检查同一列。
for (int currentRow = 0; currentRow < row; ++currentRow) {
if (chessboard[currentRow][col] == 'Q') {
return false;
}
}
// 检查左上方斜线。
for (int currentRow = row - 1, currentCol = col - 1;
currentRow >= 0 && currentCol >= 0;
--currentRow, --currentCol) {
if (chessboard[currentRow][currentCol] == 'Q') {
return false;
}
}
// 检查右上方斜线。
for (int currentRow = row - 1, currentCol = col + 1;
currentRow >= 0 && currentCol < boardSize;
--currentRow, ++currentCol) {
if (chessboard[currentRow][currentCol] == 'Q') {
return false;
}
}
return true;
}
void backtracking(
int boardSize,
int row,
vector<string>& chessboard
) {
if (row == boardSize) {
result.push_back(chessboard);
return;
}
for (int col = 0; col < boardSize; ++col) {
if (!isValid(row, col, chessboard, boardSize)) {
continue;
}
chessboard[row][col] = 'Q';
backtracking(boardSize, row + 1, chessboard);
chessboard[row][col] = '.';
}
}
public:
vector<vector<string>> solveNQueens(int n) {
result.clear();
vector<string> chessboard(n, string(n, '.'));
backtracking(n, 0, chessboard);
return result;
}
};class Solution {
private:
vector<vector<string>> result;
bool isValid(
int row,
int col,
const vector<string>& chessboard,
int boardSize
) {
// 检查同一列。
for (int currentRow = 0; currentRow < row; ++currentRow) {
if (chessboard[currentRow][col] == 'Q') {
return false;
}
}
// 检查左上方斜线。
for (int currentRow = row - 1, currentCol = col - 1;
currentRow >= 0 && currentCol >= 0;
--currentRow, --currentCol) {
if (chessboard[currentRow][currentCol] == 'Q') {
return false;
}
}
// 检查右上方斜线。
for (int currentRow = row - 1, currentCol = col + 1;
currentRow >= 0 && currentCol < boardSize;
--currentRow, ++currentCol) {
if (chessboard[currentRow][currentCol] == 'Q') {
return false;
}
}
return true;
}
void backtracking(
int boardSize,
int row,
vector<string>& chessboard
) {
if (row == boardSize) {
result.push_back(chessboard);
return;
}
for (int col = 0; col < boardSize; ++col) {
if (!isValid(row, col, chessboard, boardSize)) {
continue;
}
chessboard[row][col] = 'Q';
backtracking(boardSize, row + 1, chessboard);
chessboard[row][col] = '.';
}
}
public:
vector<vector<string>> solveNQueens(int n) {
result.clear();
vector<string> chessboard(n, string(n, '.'));
backtracking(n, 0, chessboard);
return result;
}
};搜索与剪枝
每一层表示一行,每个分支表示在该行选择一列。只有位置满足列与两条斜线约束时才继续递归,这相当于在搜索过程中提前剪去不可能产生答案的分支。
- 时间复杂度:搜索树规模通常估计为 ;当前实现每次合法性检查还需要 ,因此可估计为 ,不计结果复制
- 空间复杂度:不计结果集,棋盘占用 ,递归调用栈占用
2026-09-22(周二)
回溯算法(七)
十六、解数独
题目:37. 解数独
解数独与N 皇后都属于棋盘搜索问题,但二者的搜索结构不同:
| 对比项 | N 皇后 | 解数独 |
|---|---|---|
| 每层处理对象 | 一整行 | 一个空格 |
| 当前节点的选择 | 在某一列放置皇后 | 尝试数字 1 到 9 |
| 约束 | 列与两条斜线 | 行、列与九宫格 |
| 搜索目标 | 收集全部合法棋盘 | 找到一个解后立即结束 |
数独的每个空格都必须填入数字,因此搜索树通常比 N 皇后更宽、更深。递归时找到第一个空格,依次尝试 1 到 9;若某个数字满足约束,就继续填写下一个空格。
这里让回溯函数返回 bool:找到完整解时逐层返回 true,从而立即停止搜索。
class Solution {
private:
bool isValid(
int row,
int col,
char value,
const vector<vector<char>>& board
) {
// 检查同一行和同一列。
for (int index = 0; index < 9; ++index) {
if (board[row][index] == value ||
board[index][col] == value) {
return false;
}
}
// 检查当前 3 × 3 九宫格。
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int currentRow = startRow;
currentRow < startRow + 3;
++currentRow) {
for (int currentCol = startCol;
currentCol < startCol + 3;
++currentCol) {
if (board[currentRow][currentCol] == value) {
return false;
}
}
}
return true;
}
bool backtracking(vector<vector<char>>& board) {
for (int row = 0; row < 9; ++row) {
for (int col = 0; col < 9; ++col) {
if (board[row][col] != '.') {
continue;
}
for (char value = '1'; value <= '9'; ++value) {
if (!isValid(row, col, value, board)) {
continue;
}
board[row][col] = value;
if (backtracking(board)) {
return true;
}
board[row][col] = '.';
}
// 当前空格尝试所有数字后仍无解,说明本条路径失败。
return false;
}
}
// 没有剩余空格,说明棋盘已经填写完成。
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};class Solution {
private:
bool isValid(
int row,
int col,
char value,
const vector<vector<char>>& board
) {
// 检查同一行和同一列。
for (int index = 0; index < 9; ++index) {
if (board[row][index] == value ||
board[index][col] == value) {
return false;
}
}
// 检查当前 3 × 3 九宫格。
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int currentRow = startRow;
currentRow < startRow + 3;
++currentRow) {
for (int currentCol = startCol;
currentCol < startCol + 3;
++currentCol) {
if (board[currentRow][currentCol] == value) {
return false;
}
}
}
return true;
}
bool backtracking(vector<vector<char>>& board) {
for (int row = 0; row < 9; ++row) {
for (int col = 0; col < 9; ++col) {
if (board[row][col] != '.') {
continue;
}
for (char value = '1'; value <= '9'; ++value) {
if (!isValid(row, col, value, board)) {
continue;
}
board[row][col] = value;
if (backtracking(board)) {
return true;
}
board[row][col] = '.';
}
// 当前空格尝试所有数字后仍无解,说明本条路径失败。
return false;
}
}
// 没有剩余空格,说明棋盘已经填写完成。
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};
return false的位置只有当前空格的
1到9全部尝试失败后,才能返回false。如果把它放进数字循环内部,就会在第一个候选数字失败时过早终止。
- 时间复杂度:设空格数量为 ,粗略上界为 ;行、列和九宫格约束会剪去大量分支
- 空间复杂度:棋盘原地修改,不计棋盘本身时,递归调用栈最坏为
十七、回溯算法总结
回溯可以理解为在搜索树上进行深度优先遍历:做出选择、进入下一层、撤销选择,再尝试其他分支。
常见问题类型:
| 类型 | 目标 | 典型状态或技巧 | 示例 |
|---|---|---|---|
| 组合 | 从若干元素中按规则选择一组 | startIndex、剪枝、树层去重 | 组合 |
| 切割 | 枚举字符串的分割位置 | 起止下标、子串合法性判断 | 分割回文串 |
| 子集 | 收集满足条件的所有子集 | 收集搜索树上的节点 | 子集 |
| 排列 | 枚举考虑顺序的所有方案 | used 数组、树层去重 | 全排列 |
| 棋盘 | 在二维空间中逐步放置元素 | 位置合法性检查、提前剪枝 | N 皇后、解数独 |
通用模板:
void backtracking(路径, 选择范围) {
if (满足终止条件) {
保存结果;
return;
}
for (选择 : 当前层的可选集合) {
if (选择不合法) {
continue;
}
做出选择;
backtracking(更新后的路径, 更新后的选择范围);
撤销选择;
}
}void backtracking(路径, 选择范围) {
if (满足终止条件) {
保存结果;
return;
}
for (选择 : 当前层的可选集合) {
if (选择不合法) {
continue;
}
做出选择;
backtracking(更新后的路径, 更新后的选择范围);
撤销选择;
}
}分析回溯问题时,依次确认:
- 路径是什么:已经做出的选择如何保存?
- 每层有哪些选择:循环范围是什么,是否需要
startIndex或used? - 何时收集结果:收集叶子节点、所有节点,还是部分合法节点?
- 终止条件是什么:路径长度、剩余目标值、字符串末尾或棋盘填满?
- 如何剪枝与去重:哪些分支一定无解,重复发生在树层还是树枝?
- 如何撤销选择:递归返回后,需要恢复哪些路径、标记或棋盘状态?
核心
回溯的本质不是记忆不同题目的代码,而是明确搜索树的节点状态、选择集合、终止条件、结果收集位置、剪枝规则和撤销操作。
2026-09-25(周五)
近况
这几天去云南比赛啦,偷个小懒;趁今天下午没事,抓紧学一会儿。
贪心算法(一)
一、贪心算法理论基础
贪心算法的核心是:在每个阶段选择当前看来最优的方案,并证明这些局部最优选择最终能够构成全局最优解。
真正的难点不在代码,而在于回答两个问题:
- 当前阶段的“局部最优”是什么?
- 为什么采用这个局部最优后,不会错过全局最优解?
常见分析步骤:
- 明确问题的全局目标。
- 找出每个阶段可执行的选择。
- 提出局部最优的贪心策略。
- 证明该选择具有安全性,不会排除全局最优解。
- 重复选择并组合得到最终答案。
常见证明思路包括:
- 交换论证:证明任意最优解都可以替换为当前贪心选择,而不会变差。
- 归纳法:证明完成一次贪心选择后,剩余问题仍具有相同结构。
- 领先法 / 不变式:证明贪心方案在每一步都不会落后于其他可行方案。
举不出反例不等于证明正确
尝试构造反例可以快速否定错误的贪心策略,但“暂时找不到反例”不能证明策略一定正确。最终仍需要交换论证、归纳或不变式等理由说明局部最优能够推出全局最优。若当前决策会影响后续状态,通常还要考虑动态规划。
二、分发饼干
题目:455. 分发饼干
先将孩子胃口和饼干尺寸分别排序,可以从两个方向理解贪心策略:
| 方向 | 局部最优 | 实现方式 |
|---|---|---|
| 从大到小 | 用最大的饼干优先满足胃口最大的孩子 | 遍历孩子,维护最大饼干下标 |
| 从小到大 | 用能满足当前孩子的最小饼干,保留大饼干 | 遍历饼干,维护最小胃口下标 |
两种策略都能避免资源浪费,从而使被满足的孩子数量最大。
写法一:大饼干优先满足大胃口
class Solution {
public:
int findContentChildren(
vector<int>& greed,
vector<int>& cookies
) {
sort(greed.begin(), greed.end());
sort(cookies.begin(), cookies.end());
int cookieIndex = static_cast<int>(cookies.size()) - 1;
int result = 0;
for (int childIndex = static_cast<int>(greed.size()) - 1;
childIndex >= 0;
--childIndex) {
if (cookieIndex >= 0 &&
cookies[cookieIndex] >= greed[childIndex]) {
++result;
--cookieIndex;
}
}
return result;
}
};class Solution {
public:
int findContentChildren(
vector<int>& greed,
vector<int>& cookies
) {
sort(greed.begin(), greed.end());
sort(cookies.begin(), cookies.end());
int cookieIndex = static_cast<int>(cookies.size()) - 1;
int result = 0;
for (int childIndex = static_cast<int>(greed.size()) - 1;
childIndex >= 0;
--childIndex) {
if (cookieIndex >= 0 &&
cookies[cookieIndex] >= greed[childIndex]) {
++result;
--cookieIndex;
}
}
return result;
}
};写法二:小饼干优先满足小胃口
class Solution {
public:
int findContentChildren(
vector<int>& greed,
vector<int>& cookies
) {
sort(greed.begin(), greed.end());
sort(cookies.begin(), cookies.end());
int childIndex = 0;
for (int cookie : cookies) {
if (childIndex < static_cast<int>(greed.size()) &&
cookie >= greed[childIndex]) {
++childIndex;
}
}
return childIndex;
}
};class Solution {
public:
int findContentChildren(
vector<int>& greed,
vector<int>& cookies
) {
sort(greed.begin(), greed.end());
sort(cookies.begin(), cookies.end());
int childIndex = 0;
for (int cookie : cookies) {
if (childIndex < static_cast<int>(greed.size()) &&
cookie >= greed[childIndex]) {
++childIndex;
}
}
return childIndex;
}
};- 时间复杂度:,主要开销来自两次排序
- 空间复杂度:除排序所需空间外为
三、摆动序列
题目:376. 摆动序列
在一段连续上升或连续下降的坡度中,中间节点不会增加摆动次数,可以只保留坡度两端的极值点。
- 局部最优:删除单调坡度中的中间节点,只保留峰值和谷值。
- 全局最优:保留尽可能多的局部极值,得到最长摆动子序列。
实现时记录前一个有效坡度 previousDifference。只有当前坡度与前一个有效坡度方向相反时,才出现新的峰值或谷值,并更新前一个坡度。
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int previousDifference = 0;
int result = 1;
for (int index = 0;
index + 1 < static_cast<int>(nums.size());
++index) {
int currentDifference = nums[index + 1] - nums[index];
bool changesToUp =
previousDifference <= 0 && currentDifference > 0;
bool changesToDown =
previousDifference >= 0 && currentDifference < 0;
if (changesToUp || changesToDown) {
++result;
// 只在出现有效摆动时更新,忽略平坡和同向坡度。
previousDifference = currentDifference;
}
}
return result;
}
};class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int previousDifference = 0;
int result = 1;
for (int index = 0;
index + 1 < static_cast<int>(nums.size());
++index) {
int currentDifference = nums[index + 1] - nums[index];
bool changesToUp =
previousDifference <= 0 && currentDifference > 0;
bool changesToDown =
previousDifference >= 0 && currentDifference < 0;
if (changesToUp || changesToDown) {
++result;
// 只在出现有效摆动时更新,忽略平坡和同向坡度。
previousDifference = currentDifference;
}
}
return result;
}
};为什么只在摆动时更新
previousDifference连续同向坡度中只需要保留最远端的极值。如果每一步都更新前一个有效坡度,遇到相等元素或平台时容易破坏对峰值、谷值的判断。
- 时间复杂度:
- 空间复杂度:
2026-10-01(周四)
贪心算法(二)
四、买卖股票的最佳时机 II
本题允许完成多笔交易,关键是把一段交易利润拆成相邻两天的价格差。
例如,第 0 天买入、第 3 天卖出的利润为:
因此,无须真正记录买入和卖出的区间,只需累加所有正的相邻日利润:
- 局部最优:只收集
prices[i] - prices[i - 1] > 0的利润。 - 全局最优:所有正利润相加,得到可实现的最大总利润。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int totalProfit = 0;
for (int day = 1;
day < static_cast<int>(prices.size());
++day) {
int dailyProfit = prices[day] - prices[day - 1];
if (dailyProfit > 0) {
totalProfit += dailyProfit;
}
}
return totalProfit;
}
};class Solution {
public:
int maxProfit(vector<int>& prices) {
int totalProfit = 0;
for (int day = 1;
day < static_cast<int>(prices.size());
++day) {
int dailyProfit = prices[day] - prices[day - 1];
if (dailyProfit > 0) {
totalProfit += dailyProfit;
}
}
return totalProfit;
}
};适用前提
这种“累加所有正差值”的方法依赖于本题允许多次交易。若交易次数、手续费或冷冻期受到限制,就不能直接套用该结论。
- 时间复杂度:
- 空间复杂度:
2026-10-02(周五)
贪心算法(三)
五、跳跃游戏
题目:55. 跳跃游戏
本题无须确定每一步具体跳到哪里,只需维护从已知可达位置出发,能够覆盖到的最远下标 farthest。
遍历过程中,当前位置必须满足 index <= farthest,否则当前位置本身不可达,也就无法继续扩展覆盖范围。对于每个可达位置,使用以下公式更新覆盖范围:
farthest = max(farthest, index + nums[index]);farthest = max(farthest, index + nums[index]);- 局部最优:不断扩大当前能够到达的最远位置。
- 全局目标:判断最大覆盖范围能否到达数组末尾。
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.empty()) {
return false;
}
int farthest = 0;
int lastIndex = static_cast<int>(nums.size()) - 1;
for (int index = 0;
index <= farthest && index <= lastIndex;
++index) {
farthest = max(farthest, index + nums[index]);
if (farthest >= lastIndex) {
return true;
}
}
return false;
}
};class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.empty()) {
return false;
}
int farthest = 0;
int lastIndex = static_cast<int>(nums.size()) - 1;
for (int index = 0;
index <= farthest && index <= lastIndex;
++index) {
farthest = max(farthest, index + nums[index]);
if (farthest >= lastIndex) {
return true;
}
}
return false;
}
};不是“每次都跳最远”
算法并没有真的决定某一步落在哪里,而是合并所有已知可达位置能够产生的覆盖范围。只要终点进入覆盖范围,就一定存在一条可达路径。
- 时间复杂度:
- 空间复杂度:
六、跳跃游戏 II
题目:45. 跳跃游戏 II
在保证一定能够到达终点的前提下,需要求最少跳跃次数。遍历时维护两个边界:
| 状态 | 含义 |
|---|---|
currentEnd | 使用当前跳跃次数能够覆盖的最远位置 |
nextEnd | 在当前覆盖区间内再跳一步,能够到达的最远位置 |
在到达 currentEnd 之前,持续更新 nextEnd。当遍历到当前边界时,说明必须再跳一步,并将当前边界更新为 nextEnd。这相当于按层遍历隐式图:每扩展一层,跳跃次数增加一次。
class Solution {
public:
int jump(vector<int>& nums) {
int jumps = 0;
int currentEnd = 0;
int nextEnd = 0;
// 到达最后一个下标后无需继续起跳。
for (int index = 0;
index + 1 < static_cast<int>(nums.size());
++index) {
nextEnd = max(nextEnd, index + nums[index]);
if (index == currentEnd) {
++jumps;
currentEnd = nextEnd;
}
}
return jumps;
}
};class Solution {
public:
int jump(vector<int>& nums) {
int jumps = 0;
int currentEnd = 0;
int nextEnd = 0;
// 到达最后一个下标后无需继续起跳。
for (int index = 0;
index + 1 < static_cast<int>(nums.size());
++index) {
nextEnd = max(nextEnd, index + nums[index]);
if (index == currentEnd) {
++jumps;
currentEnd = nextEnd;
}
}
return jumps;
}
};为什么循环不遍历最后一个位置
跳跃次数表示“从当前位置起跳”的次数。到达终点后不需要再跳,所以循环只遍历到倒数第二个下标,避免多统计一步。
- 时间复杂度:
- 空间复杂度:
2026-10-04(周日)
贪心算法(四)
七、K 次取反后最大化的数组和
为了让数组和尽可能大,需要分两阶段进行贪心选择:
- 优先反转绝对值大的负数:负数
-x变成x后,数组和增加2x,因此绝对值越大,收益越大。 - 处理剩余次数:所有负数都变为非负数后,如果
k仍为奇数,就反转绝对值最小的数,使损失最小;若k为偶数,重复反转同一个数即可相互抵消。
因此,可以先按绝对值从大到小排序。完成负数反转后,数组末尾自然是绝对值最小的元素。
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(
nums.begin(),
nums.end(),
[](int left, int right) {
return abs(left) > abs(right);
}
);
for (int& number : nums) {
if (number < 0 && k > 0) {
number = -number;
--k;
}
}
// 剩余奇数次操作时,反转绝对值最小的元素。
if (k % 2 == 1) {
nums.back() = -nums.back();
}
int result = 0;
for (int number : nums) {
result += number;
}
return result;
}
};class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(
nums.begin(),
nums.end(),
[](int left, int right) {
return abs(left) > abs(right);
}
);
for (int& number : nums) {
if (number < 0 && k > 0) {
number = -number;
--k;
}
}
// 剩余奇数次操作时,反转绝对值最小的元素。
if (k % 2 == 1) {
nums.back() = -nums.back();
}
int result = 0;
for (int number : nums) {
result += number;
}
return result;
}
};看绝对值,不是只看最小正整数
处理完负数后,剩余操作应落在绝对值最小的元素上。该元素可能是正数,也可能是
0;如果存在0,无论反转多少次都不会改变数组和。
- 时间复杂度:,主要开销来自排序
- 空间复杂度:除排序所需空间外为
八、加油站
题目:134. 加油站
令每个加油站的油量盈余为:
需要同时维护两个量:
| 状态 | 含义 | 用途 |
|---|---|---|
totalBalance | 整个环路的总油量盈余 | 判断是否存在可行起点 |
currentBalance | 从当前候选起点到当前位置的油量盈余 | 判断当前候选起点是否失败 |
贪心策略:
- 如果
totalBalance < 0,总油量小于总消耗,从任何位置出发都无法绕行一周。 - 如果从候选起点到位置
i时currentBalance < 0,说明该区间内的任意位置都不能作为起点,可以直接把候选起点移动到i + 1。 - 如果最终
totalBalance >= 0,最后保留下来的候选起点一定可行。
class Solution {
public:
int canCompleteCircuit(
vector<int>& gas,
vector<int>& cost
) {
int totalBalance = 0;
int currentBalance = 0;
int startIndex = 0;
for (int index = 0;
index < static_cast<int>(gas.size());
++index) {
int balance = gas[index] - cost[index];
totalBalance += balance;
currentBalance += balance;
if (currentBalance < 0) {
startIndex = index + 1;
currentBalance = 0;
}
}
return totalBalance >= 0 ? startIndex : -1;
}
};class Solution {
public:
int canCompleteCircuit(
vector<int>& gas,
vector<int>& cost
) {
int totalBalance = 0;
int currentBalance = 0;
int startIndex = 0;
for (int index = 0;
index < static_cast<int>(gas.size());
++index) {
int balance = gas[index] - cost[index];
totalBalance += balance;
currentBalance += balance;
if (currentBalance < 0) {
startIndex = index + 1;
currentBalance = 0;
}
}
return totalBalance >= 0 ? startIndex : -1;
}
};前缀和视角
若从下标
0开始计算前缀油量,途中从未为负,则0可以作为起点。若最低前缀为负,就需要跳过造成亏空的前缀区间;上面的“一旦区间和为负,就把起点移动到下一站”正是在一次遍历中完成这一过程。
- 时间复杂度:
- 空间复杂度:
2026-10-05(周一)
贪心算法(五)
九、分发糖果
题目:135. 分发糖果
每个孩子至少得到一颗糖果;若某个孩子的评分高于相邻孩子,那么他获得的糖果也必须更多。
左右两个方向的约束不能在一次遍历中同时确定,否则修改一侧时可能破坏另一侧已经满足的关系。可以把问题拆成两次单向贪心:
| 遍历方向 | 处理的约束 | 更新方式 |
|---|---|---|
| 从左到右 | 当前评分高于左侧 | candies[i] = candies[i - 1] + 1 |
| 从右到左 | 当前评分高于右侧 | candies[i] = max(candies[i], candies[i + 1] + 1) |
第二次遍历必须取最大值:既要满足右侧约束,也不能破坏第一次遍历已经满足的左侧约束。
class Solution {
public:
int candy(vector<int>& ratings) {
int childCount = static_cast<int>(ratings.size());
vector<int> candies(childCount, 1);
// 满足“右侧评分更高”时的左邻居约束。
for (int index = 1; index < childCount; ++index) {
if (ratings[index] > ratings[index - 1]) {
candies[index] = candies[index - 1] + 1;
}
}
// 满足“左侧评分更高”时的右邻居约束。
for (int index = childCount - 2; index >= 0; --index) {
if (ratings[index] > ratings[index + 1]) {
candies[index] = max(
candies[index],
candies[index + 1] + 1
);
}
}
int totalCandies = 0;
for (int count : candies) {
totalCandies += count;
}
return totalCandies;
}
};class Solution {
public:
int candy(vector<int>& ratings) {
int childCount = static_cast<int>(ratings.size());
vector<int> candies(childCount, 1);
// 满足“右侧评分更高”时的左邻居约束。
for (int index = 1; index < childCount; ++index) {
if (ratings[index] > ratings[index - 1]) {
candies[index] = candies[index - 1] + 1;
}
}
// 满足“左侧评分更高”时的右邻居约束。
for (int index = childCount - 2; index >= 0; --index) {
if (ratings[index] > ratings[index + 1]) {
candies[index] = max(
candies[index],
candies[index + 1] + 1
);
}
}
int totalCandies = 0;
for (int count : candies) {
totalCandies += count;
}
return totalCandies;
}
};相同评分无须额外处理
题目只要求评分更高的孩子获得更多糖果。相邻孩子评分相同时,二者的糖果数量没有大小约束。
- 时间复杂度:
- 空间复杂度:,用于保存每个孩子的糖果数量
十、柠檬水找零
题目:860. 柠檬水找零
每杯柠檬水售价为 5 美元,顾客只会支付 5、10 或 20 美元:
- 收到
5美元:无须找零,增加一张5美元。 - 收到
10美元:必须使用一张5美元找零。 - 收到
20美元:优先使用一张10美元和一张5美元;若无法这样找零,再尝试使用三张5美元。
5 美元既能为 10 美元账单找零,也能为 20 美元账单找零;10 美元只能用于 20 美元账单。因此,处理 20 美元时优先消耗一张 10 美元,可以尽量保留用途更广的 5 美元。
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int fiveDollarCount = 0;
int tenDollarCount = 0;
for (int bill : bills) {
if (bill == 5) {
++fiveDollarCount;
} else if (bill == 10) {
if (fiveDollarCount == 0) {
return false;
}
--fiveDollarCount;
++tenDollarCount;
} else {
if (tenDollarCount > 0 && fiveDollarCount > 0) {
--tenDollarCount;
--fiveDollarCount;
} else if (fiveDollarCount >= 3) {
fiveDollarCount -= 3;
} else {
return false;
}
}
}
return true;
}
};class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int fiveDollarCount = 0;
int tenDollarCount = 0;
for (int bill : bills) {
if (bill == 5) {
++fiveDollarCount;
} else if (bill == 10) {
if (fiveDollarCount == 0) {
return false;
}
--fiveDollarCount;
++tenDollarCount;
} else {
if (tenDollarCount > 0 && fiveDollarCount > 0) {
--tenDollarCount;
--fiveDollarCount;
} else if (fiveDollarCount >= 3) {
fiveDollarCount -= 3;
} else {
return false;
}
}
}
return true;
}
};无须记录
20美元后续找零只会用到
5美元和10美元,收到的20美元无法参与任何一种找零方案,因此不需要维护其数量。
- 时间复杂度:
- 空间复杂度:
2026-10-06(周二)
贪心算法(六)
十一、根据身高重建队列
每个人用 [height, k] 表示,其中 k 是排在他前面且身高大于等于 height 的人数。题目同时包含“身高”和“人数”两个维度,处理原则是:先确定一个维度,再利用已经确定的顺序处理另一个维度。
具体策略:
- 按身高从高到低排序。
- 身高相同时,按
k从小到大排序。 - 按排序后的顺序,将每个人插入结果队列的下标
k处。
处理当前人物时,队列中已经存在的人都不比他矮。因此,插入到下标 k 后,前面恰好有 k 个身高大于等于他的人;后续插入的更矮人物不会影响这一条件。
class Solution {
public:
vector<vector<int>> reconstructQueue(
vector<vector<int>>& people
) {
sort(
people.begin(),
people.end(),
[](const vector<int>& left, const vector<int>& right) {
if (left[0] == right[0]) {
return left[1] < right[1];
}
return left[0] > right[0];
}
);
vector<vector<int>> queue;
for (const vector<int>& person : people) {
queue.insert(queue.begin() + person[1], person);
}
return queue;
}
};class Solution {
public:
vector<vector<int>> reconstructQueue(
vector<vector<int>>& people
) {
sort(
people.begin(),
people.end(),
[](const vector<int>& left, const vector<int>& right) {
if (left[0] == right[0]) {
return left[1] < right[1];
}
return left[0] > right[0];
}
);
vector<vector<int>> queue;
for (const vector<int>& person : people) {
queue.insert(queue.begin() + person[1], person);
}
return queue;
}
};同身高时为什么按
k升序身高相同的人彼此都满足“大于等于当前身高”。先插入
k较小的人,才能保证后续人物可以插入到自己的合法位置,并维持已经建立的相对关系。
- 时间复杂度:排序为 ,
vector中间插入最坏为 ,整体为 - 空间复杂度:,用于保存重建后的队列
十二、用最少数量的箭引爆气球
将每个气球视为一个闭区间。若多个气球存在公共重叠区间,就可以在公共区间内射出一支箭,同时引爆这些气球。
- 局部最优:尽量让当前箭覆盖所有仍有公共交集的气球。
- 全局最优:把气球划分为尽可能少的重叠组,每组只使用一支箭。
先按左边界升序排序,再维护当前重叠组的最小右边界 overlapEnd:
- 若下一个气球的左边界大于
overlapEnd,说明与当前组没有交集,需要新增一支箭。 - 否则仍属于当前重叠组,并收紧公共区间的右边界。
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) {
return 0;
}
sort(
points.begin(),
points.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[0] < right[0];
}
);
int arrowCount = 1;
int overlapEnd = points[0][1];
for (int index = 1;
index < static_cast<int>(points.size());
++index) {
if (points[index][0] > overlapEnd) {
++arrowCount;
overlapEnd = points[index][1];
} else {
overlapEnd = min(overlapEnd, points[index][1]);
}
}
return arrowCount;
}
};class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) {
return 0;
}
sort(
points.begin(),
points.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[0] < right[0];
}
);
int arrowCount = 1;
int overlapEnd = points[0][1];
for (int index = 1;
index < static_cast<int>(points.size());
++index) {
if (points[index][0] > overlapEnd) {
++arrowCount;
overlapEnd = points[index][1];
} else {
overlapEnd = min(overlapEnd, points[index][1]);
}
}
return arrowCount;
}
};判断条件是
>,不是>=气球区间包含端点。当下一个气球的左边界等于当前重叠区间的右边界时,仍可以在该端点射出一支箭,同时引爆两个气球。
- 时间复杂度:,主要开销来自排序
- 空间复杂度:除排序所需空间外为
2026-10-08(周四)
贪心算法(七)
十三、无重叠区间
题目:435. 无重叠区间
问题要求移除最少数量的区间,使剩余区间互不重叠。可以转换为:保留尽可能多的非重叠区间,再用区间总数减去保留数量。
按右边界从小到大排序,每次优先保留结束最早的区间,可以为后面的区间留下更大的可选空间:
- 默认保留第一个区间,并记录其右边界
previousEnd。 - 若下一个区间的左边界大于等于
previousEnd,两者不重叠,可以保留该区间。 - 最终用区间总数减去保留数量,得到最少移除数量。
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) {
return 0;
}
sort(
intervals.begin(),
intervals.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[1] < right[1];
}
);
int keptCount = 1;
int previousEnd = intervals[0][1];
for (int index = 1;
index < static_cast<int>(intervals.size());
++index) {
if (intervals[index][0] >= previousEnd) {
++keptCount;
previousEnd = intervals[index][1];
}
}
return static_cast<int>(intervals.size()) - keptCount;
}
};class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) {
return 0;
}
sort(
intervals.begin(),
intervals.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[1] < right[1];
}
);
int keptCount = 1;
int previousEnd = intervals[0][1];
for (int index = 1;
index < static_cast<int>(intervals.size());
++index) {
if (intervals[index][0] >= previousEnd) {
++keptCount;
previousEnd = intervals[index][1];
}
}
return static_cast<int>(intervals.size()) - keptCount;
}
};为什么选择最早结束的区间
在已经按右边界排序的情况下,选择当前最早结束的区间不会减少后续可容纳的区间数量,反而为后续选择保留了最大的空间。
- 时间复杂度:,主要开销来自排序
- 空间复杂度:除排序所需空间外为
十四、划分字母区间
题目:763. 划分字母区间
目标是让同一个字母最多出现在一个片段中。分割点必须位于当前片段内所有字符最后出现位置的最远边界之后。
处理步骤:
- 统计每个字符最后出现的下标。
- 从左向右扫描字符串,不断更新当前片段的最远右边界。
- 当当前下标等于最远右边界时,说明片段中出现过的所有字符都不会在后面再次出现,可以安全分割。
class Solution {
public:
vector<int> partitionLabels(string s) {
array<int, 26> lastPosition{};
for (int index = 0;
index < static_cast<int>(s.size());
++index) {
lastPosition[s[index] - 'a'] = index;
}
vector<int> result;
int segmentStart = 0;
int segmentEnd = 0;
for (int index = 0;
index < static_cast<int>(s.size());
++index) {
segmentEnd = max(
segmentEnd,
lastPosition[s[index] - 'a']
);
if (index == segmentEnd) {
result.push_back(segmentEnd - segmentStart + 1);
segmentStart = index + 1;
}
}
return result;
}
};class Solution {
public:
vector<int> partitionLabels(string s) {
array<int, 26> lastPosition{};
for (int index = 0;
index < static_cast<int>(s.size());
++index) {
lastPosition[s[index] - 'a'] = index;
}
vector<int> result;
int segmentStart = 0;
int segmentEnd = 0;
for (int index = 0;
index < static_cast<int>(s.size());
++index) {
segmentEnd = max(
segmentEnd,
lastPosition[s[index] - 'a']
);
if (index == segmentEnd) {
result.push_back(segmentEnd - segmentStart + 1);
segmentStart = index + 1;
}
}
return result;
}
};分割点的含义
index == segmentEnd表示当前片段内所有字符的最后出现位置都没有越过此处。若提前切割,就会让某个字符同时出现在两个片段中。
- 时间复杂度:
- 空间复杂度:,字符集大小固定为
26
十五、合并区间
题目:56. 合并区间
先按左边界从小到大排序,使可能重叠的区间相邻。将第一个区间放入结果集后,依次处理后续区间:
- 若新区间的左边界小于等于结果集中最后一个区间的右边界,说明二者重叠,只需扩大右边界。
- 否则二者不重叠,将新区间直接加入结果集。
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.empty()) {
return {};
}
sort(
intervals.begin(),
intervals.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[0] < right[0];
}
);
vector<vector<int>> result;
result.push_back(intervals[0]);
for (int index = 1;
index < static_cast<int>(intervals.size());
++index) {
if (intervals[index][0] <= result.back()[1]) {
result.back()[1] = max(
result.back()[1],
intervals[index][1]
);
} else {
result.push_back(intervals[index]);
}
}
return result;
}
};class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.empty()) {
return {};
}
sort(
intervals.begin(),
intervals.end(),
[](const vector<int>& left, const vector<int>& right) {
return left[0] < right[0];
}
);
vector<vector<int>> result;
result.push_back(intervals[0]);
for (int index = 1;
index < static_cast<int>(intervals.size());
++index) {
if (intervals[index][0] <= result.back()[1]) {
result.back()[1] = max(
result.back()[1],
intervals[index][1]
);
} else {
result.push_back(intervals[index]);
}
}
return result;
}
};三道区间题的边界判断
- 引爆气球:
nextStart > overlapEnd时才需要新箭,端点相接仍可共用一支箭。- 无重叠区间:
nextStart >= previousEnd时可以同时保留,端点相接不算重叠。- 合并区间:
nextStart <= mergedEnd时需要合并,端点相接也会合并。
- 时间复杂度:,主要开销来自排序
- 空间复杂度:不计结果集,除排序所需空间外为
2026-10-09(周五)
贪心算法(八)
十六、单调递增的数字
题目:738. 单调递增的数字
目标是找到不大于 n 的最大整数,使其各位数字从左到右非递减,即允许相邻数字相等。
如果相邻两位出现 digits[index - 1] > digits[index],就需要将左侧数字减一,并把右侧后缀全部改为 9:高位减小后,后缀取最大值才能让结果尽可能大。
处理步骤:
- 将整数转换为字符串,从右向左检查相邻数字。
- 发现逆序时,将左侧数字减一,并记录后缀的起点
suffixStart。 - 继续向左检查,因为减一可能产生新的逆序。
- 检查结束后,把
suffixStart及其右侧的所有数字统一改为9。
例如,332 的处理过程为:332 → 322 → 222 → 299。其中 322 和 222 只是中间状态,最后才统一填充后缀。
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string digits = to_string(n);
int digitCount = static_cast<int>(digits.size());
int suffixStart = digitCount;
for (int index = digitCount - 1; index > 0; --index) {
if (digits[index - 1] > digits[index]) {
--digits[index - 1];
suffixStart = index;
}
}
for (int index = suffixStart; index < digitCount; ++index) {
digits[index] = '9';
}
return stoi(digits);
}
};class Solution {
public:
int monotoneIncreasingDigits(int n) {
string digits = to_string(n);
int digitCount = static_cast<int>(digits.size());
int suffixStart = digitCount;
for (int index = digitCount - 1; index > 0; --index) {
if (digits[index - 1] > digits[index]) {
--digits[index - 1];
suffixStart = index;
}
}
for (int index = suffixStart; index < digitCount; ++index) {
digits[index] = '9';
}
return stoi(digits);
}
};为什么从右向左遍历
一位数字减一后,可能比它左边的数字更小,需要继续向高位修正。
suffixStart初始为字符串长度,保证原本已非递减的数字不会被修改;如1000最终变成0999,转换为整数后得到999。
- 时间复杂度:,其中 为十进制位数
- 空间复杂度:,用于保存数字字符串
十七、监控二叉树
题目:968. 监控二叉树
一个摄像头可以覆盖当前节点、父节点和直接子节点,不是覆盖上下三层的全部节点。优先将摄像头放在叶子节点的父节点上,通常可以比放在叶子节点上覆盖更多节点。
采用后序遍历(左、右、中),先确定左右子树的状态,再决定当前节点是否需要摄像头。
定义三个返回状态:
| 状态 | 代码名称 | 含义 |
|---|---|---|
0 | Uncovered | 当前节点尚未被覆盖,需要父节点处理 |
1 | HasCamera | 当前节点安装了摄像头 |
2 | Covered | 当前节点已被覆盖,但没有摄像头 |
按以下优先级处理:
- 至少一个孩子未覆盖:当前节点必须安装摄像头,返回
HasCamera。 - 没有未覆盖的孩子,且至少一个孩子有摄像头:当前节点已被孩子覆盖,返回
Covered。 - 两个孩子均已覆盖且都没有摄像头:当前节点暂不安装摄像头,返回
Uncovered,交给父节点处理。 - 根节点最终未覆盖:根节点没有父节点,需要补装一个摄像头。
class Solution {
private:
enum State {
Uncovered = 0,
HasCamera = 1,
Covered = 2
};
int cameraCount = 0;
State traversal(TreeNode* node) {
// 空节点不需要摄像头,也不能覆盖父节点。
if (node == nullptr) {
return Covered;
}
State leftState = traversal(node->left);
State rightState = traversal(node->right);
if (leftState == Uncovered || rightState == Uncovered) {
++cameraCount;
return HasCamera;
}
if (leftState == HasCamera || rightState == HasCamera) {
return Covered;
}
return Uncovered;
}
public:
int minCameraCover(TreeNode* root) {
cameraCount = 0;
if (traversal(root) == Uncovered) {
++cameraCount;
}
return cameraCount;
}
};class Solution {
private:
enum State {
Uncovered = 0,
HasCamera = 1,
Covered = 2
};
int cameraCount = 0;
State traversal(TreeNode* node) {
// 空节点不需要摄像头,也不能覆盖父节点。
if (node == nullptr) {
return Covered;
}
State leftState = traversal(node->left);
State rightState = traversal(node->right);
if (leftState == Uncovered || rightState == Uncovered) {
++cameraCount;
return HasCamera;
}
if (leftState == HasCamera || rightState == HasCamera) {
return Covered;
}
return Uncovered;
}
public:
int minCameraCover(TreeNode* root) {
cameraCount = 0;
if (traversal(root) == Uncovered) {
++cameraCount;
}
return cameraCount;
}
};状态判断的顺序不能交换
如果一个孩子有摄像头、另一个孩子未覆盖,孩子上的摄像头无法覆盖它的兄弟节点,当前节点仍须安装摄像头。因此必须优先判断“是否存在未覆盖的孩子”。空节点返回
Covered,也使叶子节点自然返回Uncovered,把安装摄像头的机会留给父节点。
- 时间复杂度:,每个节点只访问一次
- 空间复杂度:,用于递归调用栈; 为树高,最坏为
2026-10-10(周六)
贪心算法(九)
十八、贪心算法总结
贪心算法的核心是:每一步选择局部最优,并说明这些选择为什么能够推出全局最优。
- 判断一个解法是否属于贪心,要明确它的局部最优选择是什么,以及为什么不会影响最终的最优解。
- 如果只是按题意逐步执行,没有最优选择的依据,可能只是模拟,不能仅凭代码只有一轮遍历就认定是贪心。
- 做题时,可以先提出一个贪心策略,手动模拟典型情况和边界情况,尝试寻找反例,再决定是否实现。
- 面试中,除了写出代码和通过测试,还应解释策略正确的理由,以及时间、空间复杂度。
没找到反例,不等于已经证明正确
手动模拟和测试可以帮助验证思路,但有限的测试用例不能替代正确性论证。可以通过交换论证、归纳或不变式等方式,说明局部选择不会让全局结果变差。
相关笔记:贪心算法理论基础。
动态规划(一)
一、动态规划理论基础
动态规划(Dynamic Programming,简称 DP)把问题拆成子问题,保存已求出的状态,再通过状态转移推导后续状态,从而避免重复计算。
- 重叠子问题:相同的子问题会被多次求解,保存结果可以减少重复计算。
- 对于最优化问题,还需要合适的状态定义和最优子结构,使原问题的最优解能够由相关子问题的最优解构成。
与贪心的区别:
| 方法 | 核心思路 |
|---|---|
| 贪心 | 每一步直接采用局部最优选择,需要说明该选择不会损害全局最优 |
| 动态规划 | 保存子问题的结果,通过状态转移求出后续状态;求最优值时,通常会比较多个候选转移 |
状态不一定只依赖“上一个”状态
一个状态可能依赖多个较早的状态,也可能依赖二维表中的其他位置。遍历顺序要由状态之间的依赖关系决定。
解题五步:
- 确定状态含义:明确
dp数组(或表)及每个下标表示什么。 - 确定递推公式:说明当前状态如何由已知状态得到。
- 确定初始化:设置递推的起点和边界状态。
- 确定遍历顺序:保证计算当前状态时,它依赖的状态已经求出。
- 举例推导:手动模拟一个小例子,检查状态值和最终答案。
调试方法:
- 写代码前,先在纸上模拟一次状态转移,确认初始化和遍历方向。
- 把
dp数组打印出来,逐项与手动推导的结果比较。 - 出错时依次检查:状态定义、递推公式、初始化、遍历顺序以及答案所在的位置。
- 使用滚动数组后,重点检查更新顺序,避免覆盖后续计算仍需要的旧状态。
二、斐波那契数
题目:509. 斐波那契数
给定非负整数 n,求第 n 个斐波那契数;题目范围为 0 <= n <= 30。
按照动态规划五步分析:
- 状态含义:
dp[i]表示第i个斐波那契数。 - 递推公式:
dp[i] = dp[i - 1] + dp[i - 2],适用于i >= 2。 - 初始化:
dp[0] = 0、dp[1] = 1;当n <= 1时直接返回n。 - 遍历顺序:从前向后,因为当前状态依赖前两个状态。
- 举例推导:
i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dp[i] | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
空间优化:滚动数组
计算当前值只需要前两个状态,无须维护整个 dp 数组。每轮计算前,dp[0] 和 dp[1] 分别保存 F(i - 2) 与 F(i - 1)。
class Solution {
public:
int fib(int n) {
if (n <= 1) {
return n;
}
int dp[2] = {0, 1};
for (int i = 2; i <= n; ++i) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};class Solution {
public:
int fib(int n) {
if (n <= 1) {
return n;
}
int dp[2] = {0, 1};
for (int i = 2; i <= n; ++i) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};先求和,再移动状态
必须先用两个旧状态计算
sum,再更新dp[0]和dp[1]。本题范围内结果可用int保存;若扩大输入范围,需要重新考虑整数溢出。
- 时间复杂度:
- 空间复杂度:;若保存完整
dp数组,则为
2026-10-11(周日)
动态规划(二)
三、爬楼梯
题目:70. 爬楼梯
每次可以爬 1 或 2 个台阶,求到达第 n 阶的不同方法数。
按照动态规划五步分析:
- 状态含义:
dp[i]表示到达第i阶的方法数。 - 递推公式:
dp[i] = dp[i - 1] + dp[i - 2]。最后一步要么从第i - 1阶跨一步,要么从第i - 2阶跨两步,两类方法互不重叠,因此相加。 - 初始化:
dp[1] = 1、dp[2] = 2;本题n >= 1,n == 1时直接返回1。 - 遍历顺序:从前向后,由已知的前两个状态推出当前状态。
- 举例推导:
i | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
dp[i] | 1 | 2 | 3 | 5 | 8 |
递推形式与斐波那契数相同,但初始值和下标含义不同。若以 F(0) = 0、F(1) = 1 定义斐波那契数,则爬楼梯的方法数为 F(n + 1)。
空间优化:滚动数组
只保存前两个状态。每轮计算前,dp[0] 与 dp[1] 分别表示到达第 i - 2 阶和第 i - 1 阶的方法数。
class Solution {
public:
int climbStairs(int n) {
if (n == 1) {
return 1;
}
int dp[2] = {1, 2};
for (int i = 3; i <= n; ++i) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};class Solution {
public:
int climbStairs(int n) {
if (n == 1) {
return 1;
}
int dp[2] = {1, 2};
for (int i = 3; i <= n; ++i) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};本实现不需要定义
dp[0]对应的原始状态上面的推导从第
1、2阶开始。如果希望统一从i = 2递推,也可以定义原始状态dp[0] = 1,表示“不迈步、停在起点”这一种方法;此时dp[1] = 1,同样可以得到正确结果。不要与滚动数组中存储位置的下标混淆。
- 时间复杂度:
- 空间复杂度:
四、使用最小花费爬楼梯
cost[i] 是从第 i 个台阶向上攀爬前需要支付的费用。每次可以向上爬 1 或 2 阶,也可以直接从下标 0 或 1 的台阶开始。设 n = cost.size(),楼顶的位置是下标 n,不在 cost 数组中。
按照动态规划五步分析:
- 状态含义:
dp[i]表示到达位置i的最小花费,尚未支付从位置i离开时的费用。 - 递推公式:到达位置
i有两个来源,选择花费较小的一种:- 从
i - 1跨一步:dp[i - 1] + cost[i - 1]。 - 从
i - 2跨两步:dp[i - 2] + cost[i - 2]。 - 因此,
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])。
- 从
- 初始化:
dp[0] = 0、dp[1] = 0,因为可以直接从这两个位置开始,到达起点本身不需要费用。 - 遍历顺序:从
i = 2遍历到i = n,包含楼顶位置;最终答案是dp[n]。 - 举例推导:当
cost = [10, 15, 20]时:
位置 i | 0 | 1 | 2 | 3(楼顶) |
|---|---|---|---|---|
dp[i] | 0 | 0 | min(0 + 15, 0 + 10) = 10 | min(10 + 20, 0 + 15) = 15 |
最优路线是从位置 1 开始,支付 15,一次跨两阶到达楼顶。
空间优化:滚动状态
每轮计算前,dp0 表示 dp[i - 2],dp1 表示 dp[i - 1];先求出当前状态,再移动前两个状态。
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = static_cast<int>(cost.size());
int dp0 = 0;
int dp1 = 0;
for (int i = 2; i <= n; ++i) {
int dpi = min(dp1 + cost[i - 1], dp0 + cost[i - 2]);
dp0 = dp1;
dp1 = dpi;
}
return dp1;
}
};class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = static_cast<int>(cost.size());
int dp0 = 0;
int dp1 = 0;
for (int i = 2; i <= n; ++i) {
int dpi = min(dp1 + cost[i - 1], dp0 + cost[i - 2]);
dp0 = dp1;
dp1 = dpi;
}
return dp1;
}
};费用对应出发台阶,而不是目标位置
递推时加的是
cost[i - 1]或cost[i - 2],不是cost[i]。楼顶下标为n,没有cost[n];循环必须包含i == n,才能算出到达楼顶的最小花费。
- 时间复杂度:
- 空间复杂度:
两道爬楼梯题的区别:
| 对比项 | 爬楼梯 | 使用最小花费爬楼梯 |
|---|---|---|
| 状态含义 | 到达某一阶的方法数 | 到达某一位置的最小花费 |
| 合并方式 | 两个来源的方法数相加 | 两个来源的花费取最小值 |
| 初始化 | dp[1] = 1、dp[2] = 2 | dp[0] = 0、dp[1] = 0 |
| 目标 | 到达第 n 阶 | 到达下标为 cost.size() 的楼顶 |
2026-10-12(周一)
动态规划(三)
五、不同路径
题目:62. 不同路径
机器人从 m × n 网格的左上角 (0, 0) 出发,每次只能向右或向下移动,求到达右下角 (m - 1, n - 1) 的不同路径数。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示从(0, 0)到达(i, j)的不同路径数。 - 递推公式:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。到达当前格子的最后一步只能来自上方或左方,两类路径互不重叠,因此相加。 - 初始化:第一列
dp[i][0] = 1,第一行dp[0][j] = 1,因为只能沿同一个方向前进。 - 遍历顺序:按行从上到下、每行从左到右,保证上方和左方的状态已计算。
- 举例推导:
m = 3、n = 3时:
dp[i][j] | 第 0 列 | 第 1 列 | 第 2 列 |
|---|---|---|---|
| 第 0 行 | 1 | 1 | 1 |
| 第 1 行 | 1 | 2 | 3 |
| 第 2 行 | 1 | 3 | 6 |
最终答案为 dp[m - 1][n - 1],本例为 6。
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i) {
dp[i][0] = 1;
}
for (int j = 0; j < n; ++j) {
dp[0][j] = 1;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i) {
dp[i][0] = 1;
}
for (int j = 0; j < n; ++j) {
dp[0][j] = 1;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};单行或单列的情况
当
m == 1或n == 1时,只有一条路径。初始化已经覆盖这些情况,无须额外分支。
- 时间复杂度:
- 空间复杂度:;如果使用一维滚动数组,可降为
六、不同路径 II
题目:63. 不同路径 II
在上一题的基础上,网格中增加障碍:0 表示空地,1 表示障碍,路径不能经过障碍格子。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示从(0, 0)到达(i, j)、且不经过障碍的不同路径数。 - 递推公式:
- 当前格子为障碍时,
dp[i][j] = 0。 - 当前格子为空地时,
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。
- 当前格子为障碍时,
- 初始化:整个数组先设为
0。第一行、第一列在遇到第一个障碍之前设为1;遇到障碍后,后面的格子保持0,因为不能绕路返回这一行或这一列。 - 遍历顺序:按行从上到下、每行从左到右,和无障碍版本相同。
- 举例推导:当网格为
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]时:
dp[i][j] | 第 0 列 | 第 1 列 | 第 2 列 |
|---|---|---|---|
| 第 0 行 | 1 | 1 | 1 |
| 第 1 行 | 1 | 0(障碍) | 1 |
| 第 2 行 | 1 | 1 | 2 |
最终答案为 2。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = static_cast<int>(obstacleGrid.size());
int n = static_cast<int>(obstacleGrid[0].size());
if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) {
return 0;
}
// 题目保证最终答案不超过此上限;截断过大的中间计数。
const int pathLimit = 2000000000;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) {
dp[0][j] = 1;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (obstacleGrid[i][j] == 1) {
continue;
}
long long paths = 1LL * dp[i - 1][j] + dp[i][j - 1];
dp[i][j] = static_cast<int>(min(paths, 1LL * pathLimit));
}
}
return dp[m - 1][n - 1];
}
};class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = static_cast<int>(obstacleGrid.size());
int n = static_cast<int>(obstacleGrid[0].size());
if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) {
return 0;
}
// 题目保证最终答案不超过此上限;截断过大的中间计数。
const int pathLimit = 2000000000;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) {
dp[0][j] = 1;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (obstacleGrid[i][j] == 1) {
continue;
}
long long paths = 1LL * dp[i - 1][j] + dp[i][j - 1];
dp[i][j] = static_cast<int>(min(paths, 1LL * pathLimit));
}
}
return dp[m - 1][n - 1];
}
};障碍会截断路径
- 起点或终点有障碍时,答案直接为
0。- 第一行、第一列遇到障碍后,不能继续初始化为
1。- 障碍格子的状态必须保持
0,不能套用普通格子的相加公式。
中间计数的溢出防护
题目只保证最终答案不超过 。某些无法通向终点的区域,路径数仍可能很大。代码用
long long完成相加,再把超过上限的计数截断;此时实际保存的是min(真实路径数, pathLimit)。由于转移只有非负数相加,最终答案不超过上限时仍能得到精确结果。
- 时间复杂度:
- 空间复杂度:;如果使用一维滚动数组,可降为
改成一维滚动数组时的区别
从左到右更新时,旧的
dp[j]是上方状态,已更新的dp[j - 1]是左方状态;遇到障碍必须把dp[j]清零,不能只跳过,否则会留下上一行的路径数。
七、整数拆分
题目:343. 整数拆分
将正整数 n 拆成至少两个正整数之和,求这些整数乘积的最大值。
按照动态规划五步分析:
- 状态含义:
dp[i]表示把整数i拆成至少两个正整数后,能够得到的最大乘积。 - 递推公式:先取出一个正整数
j,剩余部分是i - j,比较两种情况:- 剩余部分不再拆分:
j * (i - j),共拆成两个数。 - 剩余部分继续拆分:
j * dp[i - j],共拆成至少三个数。 - 对每个候选
j更新:dp[i] = max({dp[i], j * (i - j), j * dp[i - j]})。
- 剩余部分不再拆分:
- 初始化:
dp[2] = 1,对应2 = 1 + 1。数组其余位置初始为0;dp[1]不是合法拆分结果,其初始值不会优于直接拆成两个数的候选。 - 遍历顺序:外层
i从小到大,因为dp[i]依赖更小的dp[i - j];内层枚举j,保留最大乘积。 - 举例推导:
i | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|
dp[i] | 1 | 2 | 4 | 6 | 9 | 12 | 18 | 27 | 36 |
例如 i = 10、j = 3 时:直接拆成 3 + 7,乘积为 21;继续拆分剩余的 7,得到 3 * dp[7] = 3 * 12 = 36,对应 3 + 3 + 4。
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n + 1, 0);
dp[2] = 1;
for (int i = 3; i <= n; ++i) {
for (int j = 1; j <= i / 2; ++j) {
int directProduct = j * (i - j);
int splitProduct = j * dp[i - j];
dp[i] = max(dp[i], max(directProduct, splitProduct));
}
}
return dp[n];
}
};class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n + 1, 0);
dp[2] = 1;
for (int i = 3; i <= n; ++i) {
for (int j = 1; j <= i / 2; ++j) {
int directProduct = j * (i - j);
int splitProduct = j * dp[i - j];
dp[i] = max(dp[i], max(directProduct, splitProduct));
}
}
return dp[n];
}
};“不拆剩余部分”与“继续拆剩余部分”都要比较
不能只使用
j * dp[i - j],因为剩余部分保持完整时可能更优。例如4 = 2 + 2得到4,而把两边都强制拆分会丢失这个候选。
为什么只枚举到
i / 2任意合法拆分至少有两个正整数,其中最小的一项必然不超过
i / 2。把这一项作为j,其余部分要么保持完整,要么由dp[i - j]求最优拆分,因此不会遗漏最优解。
- 时间复杂度:
- 空间复杂度:
2026-10-13(周二)
动态规划(四)
八、不同的二叉搜索树
题目:96. 不同的二叉搜索树
用互不相同的节点值 1 到 n 组成二叉搜索树,求结构不同的树有多少种。
根据二叉搜索树的性质,以 j 为根节点时,左子树只能使用比 j 小的值,右子树只能使用比 j 大的值。对于一组互不相同、有序的值,树的结构数量只取决于节点个数,不取决于具体数值。
按照动态规划五步分析:
- 状态含义:
dp[i]表示由i个互不相同、有序的节点值组成的二叉搜索树数量,也就是使用1到i时的数量。 - 递推公式:枚举根节点
j,左子树有j - 1个节点,右子树有i - j个节点。- 固定根节点后,左右子树的选择可以自由组合,数量为
dp[j - 1] * dp[i - j]。 - 不同根节点对应不同的树,将各根节点的结果相加:
dp[i] += dp[j - 1] * dp[i - j],其中1 <= j <= i。
- 固定根节点后,左右子树的选择可以自由组合,数量为
- 初始化:
dp[0] = 1,表示空树这一种结构;其余状态先设为0,用于累加。dp[1]会由递推自动得到1。 - 遍历顺序:外层节点数
i从小到大,内层枚举根节点j,保证左右子树的状态已经求出。 - 举例推导:
n = 3时,已知dp[0] = 1、dp[1] = 1、dp[2] = 2:
| 根节点 | 左子树节点数 | 右子树节点数 | 组合数量 |
|---|---|---|---|
1 | 0 | 2 | dp[0] * dp[2] = 2 |
2 | 1 | 1 | dp[1] * dp[1] = 1 |
3 | 2 | 0 | dp[2] * dp[0] = 2 |
所以 dp[3] = 2 + 1 + 2 = 5。
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1, 0);
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];
}
};class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1, 0);
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];
}
};空树也算一种组合
dp[0] = 1不是说有一个实际节点,而是表示“选择空子树”这一种方案。如果初始化为0,只要一侧子树为空,乘法就会把整个组合数量变成0。
- 时间复杂度:
- 空间复杂度:
九、背包理论基础(二维 0-1 背包)
有 n 件物品,第 i 件物品占用空间为 weight[i],价值为 value[i]。背包容量为 bagWeight,每件物品只能选一次,且不能拆分,求总重量不超过容量时的最大总价值。这就是 0-1 背包:每件物品只有选与不选两种选择。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示仅从下标[0, i]的物品中选择、总重量不超过容量j时,能够得到的最大总价值。不要求恰好装满。 - 递推公式:处理第
i件物品时,比较选与不选:- 不选:
dp[i - 1][j]。 - 选:
dp[i - 1][j - weight[i]] + value[i],前提是j >= weight[i]。 - 如果装不下,只能继承上一行;否则取两种选择的最大值。
- 不选:
- 初始化:
- 本题物品重量为正数,容量为
0时无法放入物品,所以dp[i][0] = 0。 - 第一行只有第
0件物品:j < weight[0]时为0;j >= weight[0]时为value[0]。 - 代码将整张表初始化为
0,因此只需要单独设置第一行中能够装下第0件物品的部分。
- 本题物品重量为正数,容量为
- 遍历顺序:先从小到大遍历物品,再遍历容量。二维写法读取的都是上一行,当前行的容量可以正序遍历。
- 举例推导:
weight = [1, 3, 4]、value = [15, 20, 30]、bagWeight = 4时:
| 可选物品 | 容量 0 | 容量 1 | 容量 2 | 容量 3 | 容量 4 |
|---|---|---|---|---|---|
| 仅物品 0 | 0 | 15 | 15 | 15 | 15 |
| 物品 0、1 | 0 | 15 | 15 | 20 | 35 |
| 物品 0、1、2 | 0 | 15 | 15 | 20 | 35 |
最终答案为 dp[n - 1][bagWeight] = 35,选择重量为 1 和 3 的两件物品。
输入与输出:
- 第一行:物品数量
n、背包容量bagWeight。 - 第二行:各物品的重量。
- 第三行:各物品的价值。
- 输出:能够装入背包的最大总价值。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, bagWeight;
if (!(cin >> n >> bagWeight)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
vector<vector<int>> dp(n, vector<int>(bagWeight + 1, 0));
// 初始化第一行:只考虑第 0 件物品。
for (int j = weight[0]; j <= bagWeight; ++j) {
dp[0][j] = value[0];
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= bagWeight; ++j) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = max(
dp[i - 1][j],
dp[i - 1][j - weight[i]] + value[i]
);
}
}
}
cout << dp[n - 1][bagWeight] << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, bagWeight;
if (!(cin >> n >> bagWeight)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
vector<vector<int>> dp(n, vector<int>(bagWeight + 1, 0));
// 初始化第一行:只考虑第 0 件物品。
for (int j = weight[0]; j <= bagWeight; ++j) {
dp[0][j] = value[0];
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= bagWeight; ++j) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = max(
dp[i - 1][j],
dp[i - 1][j - weight[i]] + value[i]
);
}
}
}
cout << dp[n - 1][bagWeight] << '\n';
return 0;
}为什么选物品时也要读取上一行
dp[i - 1][j - weight[i]]只包含之前的物品,再加上当前物品一次,才能保证每件物品最多选一次。若改成读取当前行dp[i][j - weight[i]],正序遍历时可能重复选取当前物品,就不再是 0-1 背包。
初始化不能笼统地说“任意值都可以”
第一行和容量为
0的边界必须符合状态含义。其余位置在本实现中会被完整赋值,但仍统一初始化为0,便于理解,也避免以后修改循环或改成取最大值更新时读到不正确的初始状态。
二维正序,不代表一维也能正序
将状态压缩成一维后,0-1 背包的容量需要从大到小遍历,避免本轮刚更新的状态被再次使用;这与这里读取上一行的二维写法不同。
- 时间复杂度:,其中 为背包容量
- 空间复杂度:;压缩成一维后可降为 ,物品较多或容量较大时更节省内存
2026-10-14(周三)
动态规划(五)
十、0-1 背包理论基础(滚动数组)
在二维 0-1 背包中,当前状态只依赖上一行:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
既然计算下一行时不再需要更早的行,就可以复用一维数组,省去显式复制上一行的操作。关键是更新时仍能读取到上一轮的状态,不能提前覆盖还需要使用的值。
按照动态规划五步分析:
- 状态含义:处理完当前物品后,
dp[j]表示从已处理的物品中选择、总重量不超过容量j时的最大总价值。 - 递推公式:
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])。- 更新前的
dp[j]表示不选当前物品。 - 上一轮的
dp[j - weight[i]] + value[i]表示选当前物品一次。
- 更新前的
- 初始化:
dp数组全部设为0,表示尚未选择物品时最大价值为0。这里仍是不要求恰好装满、物品重量和价值为正数的背包模型。 - 遍历顺序:外层逐件遍历物品,内层容量从
bagWeight倒序遍历到weight[i],保证较小容量的状态尚未被当前物品更新。 - 举例推导:只有一件重量为
1、价值为15的物品,背包容量为2时:
| 遍历方式 | 更新过程 | 最终结果 |
|---|---|---|
| 倒序 | 先算 dp[2] = 0 + 15,再算 dp[1] = 0 + 15 | [0, 15, 15],物品只选一次 |
| 正序 | 先算 dp[1] = 15,再用更新后的 dp[1] 算 dp[2] = 15 + 15 | [0, 15, 30],错误地重复选取同一件物品 |
倒序遍历不是为了让容量变小,而是为了保持状态来自上一轮,从而保证每件物品最多选一次。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, bagWeight;
if (!(cin >> n >> bagWeight)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
vector<int> dp(bagWeight + 1, 0);
for (int i = 0; i < n; ++i) {
for (int j = bagWeight; j >= weight[i]; --j) {
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
cout << dp[bagWeight] << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, bagWeight;
if (!(cin >> n >> bagWeight)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
vector<int> dp(bagWeight + 1, 0);
for (int i = 0; i < n; ++i) {
for (int j = bagWeight; j >= weight[i]; --j) {
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
cout << dp[bagWeight] << '\n';
return 0;
}压缩状态时,递推式和遍历方向必须一起考虑
把上一行复制到当前行后,并不能不加条件地读取已经更新的当前行。二维写法读取独立的上一行,容量可以正序;一维写法复用同一个数组,0-1 背包必须容量倒序。
- 时间复杂度:,其中 为背包容量
- 空间复杂度:DP 数组为 ;连同存储物品信息的数组,总辅助空间为
十一、分割等和子集
题目:416. 分割等和子集
判断能否将正整数数组分成两个子集,使两边的元素和相等。设总和为 sum:
- 如果
sum是奇数,无法均分,直接返回false。 - 如果
sum是偶数,只需要找到一个元素和为target = sum / 2的子集,剩余元素的和自然也是target。
因此,本题可以转化为 0-1 背包能否恰好凑出目标和:每个数组元素是一件只能使用一次的物品,其重量和价值都等于 nums[i]。
按照动态规划五步分析:
- 状态含义:
dp[j]表示从已处理的元素中选择、元素和不超过容量j时,能够得到的最大元素和。注意它不一定恰好等于j。 - 递推公式:
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]),比较不选与选当前元素一次。 - 初始化:
dp数组全部设为0,表示选择空集时元素和为0。数组长度按实际目标设为target + 1,不必固定为10001。 - 遍历顺序:外层遍历元素,内层容量从
target倒序到当前元素的值,保证每个元素只使用一次。 - 举例推导:
nums = [1, 5, 11, 5],总和为22,目标为11:
| 已处理元素 | dp[11] |
|---|---|
[1] | 1 |
[1, 5] | 6 |
[1, 5, 11] | 11 |
[1, 5, 11, 5] | 11 |
最终 dp[target] == target,可以分成 [11] 和 [1, 5, 5]。
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if (sum % 2 != 0) {
return false;
}
int target = sum / 2;
vector<int> dp(target + 1, 0);
for (int num : nums) {
for (int j = target; j >= num; --j) {
dp[j] = max(dp[j], dp[j - num] + num);
}
}
return dp[target] == target;
}
};class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if (sum % 2 != 0) {
return false;
}
int target = sum / 2;
vector<int> dp(target + 1, 0);
for (int num : nums) {
for (int j = target; j >= num; --j) {
dp[j] = max(dp[j], dp[j - num] + num);
}
}
return dp[target] == target;
}
};“不超过目标”不等于“恰好达到目标”
最终必须判断
dp[target] == target,不能只判断是否有非零结果。例如[1, 2, 5]总和为8,目标为4,但最多只能凑到3,仍然无法均分。
每个元素只能用一次,相同数值仍可来自不同位置
容量倒序是为了防止重复使用同一个元素;数组中两个值相同的元素属于两件不同物品,可以各选一次。
- 时间复杂度:,其中 为数组长度、 为总和的一半
- 空间复杂度:
2026-10-16(周五)
动态规划(六)
十二、最后一块石头的重量 II
每次选择两块石头相撞,重量相同则一起消失,否则留下重量差。求最终剩余石头重量的最小值,没有石头时为 0。
背包转化思路:
将石头分为两堆,使两堆的重量尽可能接近,就可以把问题转化为求最小重量差。设所有石头的总重量为 sum,较轻一堆的重量为 S,则:
S <= sum / 2。- 另一堆重量为
sum - S,两堆重量差为sum - 2 * S。 - 因此,只需要在不超过
target = sum / 2的前提下,让S尽可能大。
每块石头只能使用一次,其重量和价值都等于 stones[i],对应一维 0-1 背包。
按照动态规划五步分析:
- 状态含义:
dp[j]表示从已处理的石头中选择、总重量不超过容量j时,能够得到的最大总重量。 - 递推公式:
dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]),比较不选与选当前石头一次。 - 初始化:全部设为
0,表示尚未选择石头时总重量为0。数组长度按实际容量设为target + 1。 - 遍历顺序:外层遍历石头,内层容量从
target倒序到当前石头重量,保证每块石头只使用一次。 - 举例推导:
stones = [2, 7, 4, 1, 8, 1],总重量为23,背包容量为11。可以选出[7, 4],重量为11,另一堆重量为12,因此答案为23 - 2 * 11 = 1。
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int sum = 0;
for (int stone : stones) {
sum += stone;
}
int target = sum / 2;
vector<int> dp(target + 1, 0);
for (int stone : stones) {
for (int j = target; j >= stone; --j) {
dp[j] = max(dp[j], dp[j - stone] + stone);
}
}
return sum - 2 * dp[target];
}
};class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int sum = 0;
for (int stone : stones) {
sum += stone;
}
int target = sum / 2;
vector<int> dp(target + 1, 0);
for (int stone : stones) {
for (int j = target; j >= stone; --j) {
dp[j] = max(dp[j], dp[j - stone] + stone);
}
}
return sum - 2 * dp[target];
}
};不要求恰好装满一半
与分割等和子集不同,本题允许两堆重量不相等。
dp[target]是能够凑出的最大重量,不一定等于target;必须使用sum - 2 * dp[target],不能直接用sum - 2 * target。
- 时间复杂度:,其中 为石头数量、
- 空间复杂度:,
T == 0时也需要保存一个状态
十三、目标和
题目:494. 目标和
给数组中的每个非负整数添加 + 或 -,求表达式结果等于 target 的不同方案数。每个元素都要使用一次,数值相同但位置不同的元素仍分别计数。
背包转化思路:
设加正号的元素和为 left,加负号的元素和为 right,所有元素之和为 sum:
因此,问题转化为:从数组中选出元素和恰好为 bagSize = (sum + target) / 2 的子集,有多少种选法。选中的元素加正号,其余元素加负号。
先排除无解情况:
target < -sum或target > sum:超出所有符号组合能够达到的范围。sum + target为奇数:无法得到整数的子集和。
按照动态规划五步分析,使用二维数组计数:
- 状态含义:
dp[i][j]表示只使用下标[0, i]的元素,恰好凑出元素和j的子集数量。 - 递推公式:
- 不选当前元素:
dp[i - 1][j]。 - 选当前元素:当
j >= nums[i]时,有dp[i - 1][j - nums[i]]种。 - 两类方案相加:
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - nums[i]];装不下时只继承不选的方案数。
- 不选当前元素:
- 初始化:先全部设为
0,再初始化第一行:- 不选第
0个元素,dp[0][0] = 1。 - 如果
nums[0] <= bagSize,选它也贡献一种方案,所以dp[0][nums[0]] += 1。 - 当
nums[0] == 0时,两种选择落在同一个容量,dp[0][0]自然累加为2。
- 不选第
- 遍历顺序:从第
1个元素开始逐行处理,容量从0遍历到bagSize。二维数组读取上一行,容量可以正序;容量0也必须参与转移,才能正确统计后续零元素。 - 举例推导:
nums = [0, 0, 1]、target = 1,则sum = 1、bagSize = 1:
| 已处理元素 | 凑出 0 的方案数 | 凑出 1 的方案数 |
|---|---|---|
第一个 0 | 2 | 0 |
两个 0 | 4 | 0 |
[0, 0, 1] | 4 | 4 |
两个零各自可以加正号或负号,最后的 1 必须加正号,因此共有 4 种方案。题目示例 [1, 1, 1, 1, 1]、target = 3 则对应选出和为 4 的子集,共有 5 种选法。
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if (target < -sum || target > sum) {
return 0;
}
if ((target + sum) % 2 != 0) {
return 0;
}
int n = static_cast<int>(nums.size());
int bagSize = (target + sum) / 2;
vector<vector<int>> dp(n, vector<int>(bagSize + 1, 0));
dp[0][0] = 1;
if (nums[0] <= bagSize) {
dp[0][nums[0]] += 1;
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= bagSize; ++j) {
dp[i][j] = dp[i - 1][j];
if (j >= nums[i]) {
dp[i][j] += dp[i - 1][j - nums[i]];
}
}
}
return dp[n - 1][bagSize];
}
};class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if (target < -sum || target > sum) {
return 0;
}
if ((target + sum) % 2 != 0) {
return 0;
}
int n = static_cast<int>(nums.size());
int bagSize = (target + sum) / 2;
vector<vector<int>> dp(n, vector<int>(bagSize + 1, 0));
dp[0][0] = 1;
if (nums[0] <= bagSize) {
dp[0][nums[0]] += 1;
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= bagSize; ++j) {
dp[i][j] = dp[i - 1][j];
if (j >= nums[i]) {
dp[i][j] += dp[i - 1][j - nums[i]];
}
}
}
return dp[n - 1][bagSize];
}
};计数背包用相加,不是取最大值
前面的背包题求“最多能装多少”,使用
max;本题求“恰好装满有几种方案”,因此把选与不选的方案数相加。不能混用状态含义和递推公式。
零元素会使方案数翻倍
+0与-0数值相同,但属于不同的符号方案。每遇到一个零,同一个目标和的方案数都会翻倍;本题元素均非负,有k个零时,凑出和0的子集恰有2^k种。上面的初始化与递推会自动处理,无须另用浮点pow计算。
压缩成一维时的要点
初始化
dp[0] = 1,每个元素按容量倒序更新dp[j] += dp[j - num]。当num == 0时,循环仍需覆盖容量0,使每个状态恰好翻倍一次。
- 时间复杂度:,其中 ,无解情况在建表前返回
- 空间复杂度:;压缩成一维后可降为
2026-10-17(周六)
动态规划(七)
十四、一和零
题目:474. 一和零
从二进制字符串数组 strs 中选择尽可能多的字符串,使选中字符串包含的 0 总数不超过 m、1 总数不超过 n。
背包转化思路:
- 每个字符串是一件只能选择一次的物品,价值为
1,表示子集大小增加一。 - 一个字符串同时消耗两种资源:
zeroNum个零和oneNum个一。 m和n是同一个背包的两个容量约束,不是两个独立的背包;一个字符串必须整体选择,不能拆开字符来取。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示从已处理的字符串中选择,最多使用i个零、j个一时,能够得到的最大子集大小。 - 递推公式:当前字符串包含
zeroNum个零、oneNum个一,容量足够时:dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1)。- 不选当前字符串:保持原来的
dp[i][j]。 - 选当前字符串一次:从剩余容量对应的上一轮状态转移,价值加
1。
- 不选当前字符串:保持原来的
- 初始化:全部设为
0,表示不选择任何字符串时,子集大小为0。本题不要求恰好用完零和一的容量。 - 遍历顺序:外层遍历字符串;零容量从
m倒序到zeroNum,一容量从n倒序到oneNum,保证每个字符串最多选一次。 - 举例推导:
strs = ["10", "0", "1"]、m = 1、n = 1:
| 已处理字符串 | dp[1][1] | 对应选择 |
|---|---|---|
["10"] | 1 | "10" |
["10", "0"] | 1 | "10" 或 "0" |
["10", "0", "1"] | 2 | "0" 和 "1" |
最终答案为 dp[m][n] = 2。
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (const string& str : strs) {
int zeroNum = 0;
int oneNum = 0;
for (char c : str) {
if (c == '0') {
++zeroNum;
} else {
++oneNum;
}
}
for (int i = m; i >= zeroNum; --i) {
for (int j = n; j >= oneNum; --j) {
dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
}
}
}
return dp[m][n];
}
};class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (const string& str : strs) {
int zeroNum = 0;
int oneNum = 0;
for (char c : str) {
if (c == '0') {
++zeroNum;
} else {
++oneNum;
}
}
for (int i = m; i >= zeroNum; --i) {
for (int j = n; j >= oneNum; --j) {
dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
}
}
}
return dp[m][n];
}
};两个容量维度都要考虑更新方向
采用两个容量都倒序的写法,可以统一处理只含零、只含一以及同时含零和一的字符串。某一资源消耗为
0时,另一维的倒序仍能防止重复选取同一个字符串;数组中相同的字符串则属于不同物品,可以分别选择。
二维数组的两个下标都是容量
如果保留“处理到第几个字符串”这一维,完整状态会是三维的。这里已经压缩了物品维度,剩余两个下标分别表示零和一的容量,不要与物品维度加容量维度的二维背包混淆。
- 时间复杂度:,其中 为字符串数量, 为所有字符串的总长度
- 空间复杂度:
十五、完全背包理论基础
与 0-1 背包相比,完全背包的区别是:每种物品有无限件,可以重复选择。物品不能拆分,总重量不能超过背包容量,目标仍是最大总价值。
按照动态规划五步分析,先保留二维状态:
- 状态含义:
dp[i][j]表示从下标[0, i]的物品种类中选择、每种可取任意多件、总重量不超过容量j时的最大总价值。 - 递推公式:
- 不选第
i种物品:dp[i - 1][j]。 - 至少选一件第
i种物品:dp[i][j - weight[i]] + value[i],前提是j >= weight[i]。 - 因此,
dp[i][j] = max(dp[i - 1][j], dp[i][j - weight[i]] + value[i])。 - 这里读取当前行的剩余容量状态,它已经允许使用第
i种物品,再加一件就能实现重复选取。
- 不选第
- 初始化:
- 整张表先设为
0。物品重量为正数,因此容量为0时最大价值为0。 - 第一行只有第
0种物品:j < weight[0]时为0;否则尽可能重复放入,dp[0][j] = (j / weight[0]) * value[0]。
- 整张表先设为
- 遍历顺序:先遍历物品,容量从小到大。因为转移读取当前行中更小的容量,必须先算出
dp[i][j - weight[i]]。 - 举例推导:
weight = [2, 3]、value = [3, 5]、背包容量为6:
| 可选物品种类 | 容量 0 | 容量 1 | 容量 2 | 容量 3 | 容量 4 | 容量 5 | 容量 6 |
|---|---|---|---|---|---|---|---|
| 仅种类 0 | 0 | 0 | 3 | 3 | 6 | 6 | 9 |
| 种类 0、1 | 0 | 0 | 3 | 5 | 6 | 8 | 10 |
计算容量 6 时,选第 1 种物品的候选是 dp[1][3] + 5 = 10,对应重量为 3 的物品选两件。
二维核心代码(用于理解递推):
long long completeKnapsack2D(
const vector<int>& weight,
const vector<long long>& value,
int bagWeight
) {
int itemCount = static_cast<int>(weight.size());
vector<vector<long long>> dp(
itemCount,
vector<long long>(bagWeight + 1, 0)
);
for (int j = weight[0]; j <= bagWeight; ++j) {
dp[0][j] = dp[0][j - weight[0]] + value[0];
}
for (int i = 1; i < itemCount; ++i) {
for (int j = 0; j <= bagWeight; ++j) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = max(
dp[i - 1][j],
dp[i][j - weight[i]] + value[i]
);
}
}
}
return dp[itemCount - 1][bagWeight];
}long long completeKnapsack2D(
const vector<int>& weight,
const vector<long long>& value,
int bagWeight
) {
int itemCount = static_cast<int>(weight.size());
vector<vector<long long>> dp(
itemCount,
vector<long long>(bagWeight + 1, 0)
);
for (int j = weight[0]; j <= bagWeight; ++j) {
dp[0][j] = dp[0][j - weight[0]] + value[0];
}
for (int i = 1; i < itemCount; ++i) {
for (int j = 0; j <= bagWeight; ++j) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = max(
dp[i - 1][j],
dp[i][j - weight[i]] + value[i]
);
}
}
}
return dp[itemCount - 1][bagWeight];
}剩余容量状态不是“不放当前物品”
dp[i][j - weight[i]]已经可以包含第i种物品,正是这一点让完全背包能够重复选取。0-1 背包读取的是上一行dp[i - 1][j - weight[i]],两者不能混用。
一维实现(更适合题目的大规模输入):
压缩后,dp[j] 表示容量不超过 j 时的最大价值,递推为 dp[j] = max(dp[j], dp[j - weight[i]] + value[i])。与一维 0-1 背包的公式形式相同,但这里容量要正序遍历,主动使用本轮更新后的状态,允许重复选取当前物品。
输入第一行为物品种类数和背包容量,之后每行给出一种物品的重量、价值;与卡码网 46 题将重量和价值分两行输入的格式不同。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int itemCount, bagWeight;
if (!(cin >> itemCount >> bagWeight)) {
return 0;
}
vector<int> weight(itemCount);
vector<long long> value(itemCount);
for (int i = 0; i < itemCount; ++i) {
cin >> weight[i] >> value[i];
}
vector<long long> dp(bagWeight + 1, 0);
for (int i = 0; i < itemCount; ++i) {
for (int j = weight[i]; j <= bagWeight; ++j) {
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
cout << dp[bagWeight] << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int itemCount, bagWeight;
if (!(cin >> itemCount >> bagWeight)) {
return 0;
}
vector<int> weight(itemCount);
vector<long long> value(itemCount);
for (int i = 0; i < itemCount; ++i) {
cin >> weight[i] >> value[i];
}
vector<long long> dp(bagWeight + 1, 0);
for (int i = 0; i < itemCount; ++i) {
for (int j = weight[i]; j <= bagWeight; ++j) {
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
cout << dp[bagWeight] << '\n';
return 0;
}价值范围与内存开销
本题重量、价值最大可达 ,容量最大为 ,最优价值可能达到 ,因此使用
long long。物品种类和容量都较大时,二维表会占用大量内存;上面的二维代码用于理解递推,实际提交优先使用一维写法。
与 0-1 背包的对比:
| 对比项 | 0-1 背包 | 完全背包 |
|---|---|---|
| 每种物品的数量 | 最多一件 | 可以无限件 |
| 二维“选当前物品”的来源 | 上一行 dp[i - 1][j - weight[i]] | 当前行 dp[i][j - weight[i]] |
| 一维容量遍历方向 | 倒序,避免重复选取 | 正序,允许重复选取 |
| 本节目标 | 容量范围内最大价值 | 容量范围内最大价值 |
- 时间复杂度:两种写法均为 ,其中 为物品种类数、 为背包容量
- 空间复杂度:二维 DP 为 ;一维 DP 为 ,连同物品数组总辅助空间为
2026-10-19(周一)
动态规划(八)
十六、零钱兑换 II
题目:518. 零钱兑换 II
给定不同面额的硬币 coins,每种硬币都有无限枚,求恰好凑出总金额 amount 的组合数。顺序不同但硬币数量相同,算同一种组合。
这是完全背包的计数问题:不再求最大价值,而是累加恰好装满的方案数。注意题目是「零钱兑换 II」,不是求最少硬币数的「零钱兑换」。
按照动态规划五步分析,先使用二维状态:
- 状态含义:
dp[i][j]表示只使用下标[0, i]的硬币种类,恰好凑出金额j的组合数,每种可重复使用。 - 递推公式:
- 不使用当前面额:
dp[i - 1][j]。 - 至少使用一枚当前面额:
dp[i][j - coins[i]],前提是j >= coins[i]。 - 因此,
dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i]];金额不足时只继承不选的组合数。
- 不使用当前面额:
- 初始化:
- 数组先全部设为
0。 - 第一行只使用
coins[0]:当j % coins[0] == 0时有一种组合,否则没有。 - 第一列
dp[i][0] = 1:从已考虑的硬币种类中一枚都不取,恰好凑出金额0,有一种空组合。
- 数组先全部设为
- 遍历顺序:先遍历硬币种类,再从小到大遍历金额,保证上一行和当前行更小金额的状态都已求出。
- 举例推导:
coins = [1, 2, 5]、amount = 5:
| 可用面额 | 金额 0 | 金额 1 | 金额 2 | 金额 3 | 金额 4 | 金额 5 |
|---|---|---|---|---|---|---|
[1] | 1 | 1 | 1 | 1 | 1 | 1 |
[1, 2] | 1 | 1 | 2 | 2 | 3 | 3 |
[1, 2, 5] | 1 | 1 | 2 | 2 | 3 | 4 |
最终共有 4 种组合:[5]、[2, 2, 1]、[2, 1, 1, 1]、[1, 1, 1, 1, 1]。
#include <climits>
class Solution {
public:
int change(int amount, vector<int>& coins) {
int coinCount = static_cast<int>(coins.size());
vector<vector<int>> dp(coinCount, vector<int>(amount + 1, 0));
for (int j = 0; j <= amount; ++j) {
if (j % coins[0] == 0) {
dp[0][j] = 1;
}
}
for (int i = 0; i < coinCount; ++i) {
dp[i][0] = 1;
}
for (int i = 1; i < coinCount; ++i) {
for (int j = 1; j <= amount; ++j) {
dp[i][j] = dp[i - 1][j];
if (j >= coins[i]) {
long long ways = 1LL * dp[i - 1][j] + dp[i][j - coins[i]];
dp[i][j] = static_cast<int>(min(ways, 1LL * INT_MAX));
}
}
}
return dp[coinCount - 1][amount];
}
};#include <climits>
class Solution {
public:
int change(int amount, vector<int>& coins) {
int coinCount = static_cast<int>(coins.size());
vector<vector<int>> dp(coinCount, vector<int>(amount + 1, 0));
for (int j = 0; j <= amount; ++j) {
if (j % coins[0] == 0) {
dp[0][j] = 1;
}
}
for (int i = 0; i < coinCount; ++i) {
dp[i][0] = 1;
}
for (int i = 1; i < coinCount; ++i) {
for (int j = 1; j <= amount; ++j) {
dp[i][j] = dp[i - 1][j];
if (j >= coins[i]) {
long long ways = 1LL * dp[i - 1][j] + dp[i][j - coins[i]];
dp[i][j] = static_cast<int>(min(ways, 1LL * INT_MAX));
}
}
}
return dp[coinCount - 1][amount];
}
};二维循环可交换,不代表一维循环也能随意交换
保留上述二维状态时,只要两个下标都按递增顺序计算,交换两层循环仍能满足依赖关系。压缩成一维后,若要统计组合,则应外层遍历硬币、内层金额正序;交换为金额在外,会把不同顺序分别计数。
一维计数组合的写法
初始化
dp[0] = 1,其余为0。逐种硬币处理,再对金额从coin到amount正序更新dp[j] += dp[j - coin];实际实现时也要考虑中间计数的溢出。
- 时间复杂度:,其中 为硬币种类数、 为目标金额
- 空间复杂度:;压缩成一维后可降为
十七、组合总和 IV
题目:377. 组合总和 IV
给定互不相同的正整数 nums,每个数可以重复使用,求元素和为 target 的有序序列数量。虽然题名叫“组合总和”,但顺序不同会被分别计数,实际求的是排列数。
按照动态规划五步分析:
- 状态含义:
dp[i]表示元素和恰好为i的有序序列数量。 - 递推公式:枚举序列的最后一个数
num,当i >= num时,将num追加到每个和为i - num的序列后面:dp[i] += dp[i - num]。不同末尾元素对应的方案互不重叠,因此相加。 - 初始化:
dp[0] = 1,表示一种空序列;其他状态为0。这使单个数恰好等于当前目标时,也能贡献一种方案。 - 遍历顺序:外层目标和从
1递增到target,内层遍历所有候选数。因为候选数均为正数,所依赖的dp[i - num]已经算出。 - 举例推导:
nums = [1, 2, 3]、target = 4:
目标和 i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
dp[i] | 1 | 1 | 2 | 4 | 7 |
dp[4] = dp[3] + dp[2] + dp[1] = 7,对应末尾分别为 1、2、3。例如 [1, 3] 和 [3, 1] 是两种不同的序列。
#include <climits>
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (int num : nums) {
if (i >= num) {
long long ways = 1LL * dp[i] + dp[i - num];
dp[i] = static_cast<int>(min(ways, 1LL * INT_MAX));
}
}
}
return dp[target];
}
};#include <climits>
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (int num : nums) {
if (i >= num) {
long long ways = 1LL * dp[i] + dp[i - num];
dp[i] = static_cast<int>(min(ways, 1LL * INT_MAX));
}
}
}
return dp[target];
}
};同一递推形式,循环顺序改变计数对象
在本节的一维完全背包计数模型中,先遍历物品会按固定的物品处理顺序归并方案,统计组合;先遍历目标和、再枚举末尾元素,则统计排列。不能只背公式,而忽略状态在当前循环中的含义。
两段代码的中间计数防溢出
两题都保证最终答案可用有符号 32 位整数表示,但较小金额的计数不一定也满足这个范围。代码先用
long long相加,再将超出INT_MAX的计数截断,实际保存min(真实计数, INT_MAX)。由于递推只有非负计数相加,这样不会影响题目保证范围内的最终答案;也不需要假设某种更宽的整数能容纳所有中间计数。
- 时间复杂度:,其中 为候选数数量、 为目标和
- 空间复杂度:
组合与排列的对比:
| 对比项 | 零钱兑换 II | 组合总和 IV |
|---|---|---|
| 计数对象 | 不考虑顺序的组合 | 考虑顺序的序列 |
| 元素能否重复使用 | 可以 | 可以 |
| 一维外层循环 | 硬币种类 | 目标和 |
| 一维内层循环 | 金额正序 | 枚举序列的最后一个数 |
使用 [1, 2] 凑出 3 | 2 种:[1, 1, 1]、[1, 2] | 3 种:再加上 [2, 1] |
2026-10-20(周二)
动态规划(九)
十八、爬楼梯(进阶版)
题目:卡码网 57. 爬楼梯
楼梯共有 n 阶,每次可以爬 1 到 m 阶,求恰好到达楼顶的不同方法数。题目范围为 1 <= m < n <= 32。
背包转化思路:
- 楼梯总阶数
n对应背包的目标容量。 - 每次可爬的阶数
1, 2, ..., m对应可重复使用的物品。 - 步数顺序不同,算不同的方法,例如
1 + 2和2 + 1是两种走法。
因此,这是完全背包的排列计数问题,与组合总和 IV的模型相同;当 m = 2 时,就是之前的普通爬楼梯问题。
按照动态规划五步分析:
- 状态含义:
dp[i]表示恰好爬到第i阶的不同方法数。 - 递推公式:枚举最后一次爬的阶数
step,此前必须到达第i - step阶,所以dp[i] += dp[i - step],其中1 <= step <= min(m, i)。不同的最后一步对应不同的走法,方案数相加。 - 初始化:
dp[0] = 1,表示停在起点、不迈步这一种空走法,作为后续转移的起点;其余位置为0,用于累加方法数。 - 遍历顺序:外层从小到大遍历目标阶数
i,内层枚举最后一步step。由于步数为正,依赖的dp[i - step]已经求出,也能把不同步数顺序分别计数。 - 举例推导:
n = 4、m = 3时:
到达阶数 i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
dp[i] | 1 | 1 | 2 | 4 | 7 |
最后一步可爬 1、2 或 3 阶,所以 dp[4] = dp[3] + dp[2] + dp[1] = 7。题目示例 n = 3、m = 2 则有 1 + 1 + 1、1 + 2、2 + 1 三种走法。
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
while (cin >> n >> m) {
vector<long long> dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int step = 1; step <= m && step <= i; ++step) {
dp[i] += dp[i - step];
}
}
cout << dp[n] << '\n';
}
return 0;
}#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
while (cin >> n >> m) {
vector<long long> dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int step = 1; step <= m && step <= i; ++step) {
dp[i] += dp[i - step];
}
}
cout << dp[n] << '\n';
}
return 0;
}求的是走法顺序,不能改成步数在外层
外层遍历目标阶数、内层枚举最后一步,才能同时统计
1 + 2和2 + 1。如果改成先逐种处理步数、再正序遍历阶数,就会变成不考虑顺序的组合计数。
初始化与数值范围
dp[0] = 1是递推的起点,不是说已经爬了一阶;其余状态从0开始累加。代码使用long long保存计数,在本题范围内足够;若进一步扩大楼梯阶数,仍需重新评估溢出问题。
- 时间复杂度:
- 空间复杂度:
2026-10-21(周三)
动态规划(十)
十九、零钱兑换
题目:322. 零钱兑换
每种面额的硬币都有无限枚,求恰好凑出金额 amount 所需的最少硬币数;无法凑出时返回 -1。这是完全背包的最少数量问题,与零钱兑换 II 的组合计数不同。
按照动态规划五步分析:
- 状态含义:
dp[j]表示恰好凑出金额j所需的最少硬币数;不可达时使用INT_MAX标记。 - 递推公式:选择一枚面额为
coin的硬币,如果j >= coin且dp[j - coin]可达,则dp[j] = min(dp[j], dp[j - coin] + 1)。其中+1表示再使用一枚硬币。 - 初始化:
dp[0] = 0,凑出金额0不需要硬币;其余状态设为INT_MAX,表示尚未找到可行方案,不能初始化为0。 - 遍历顺序:外层遍历硬币,内层金额从
coin到amount正序遍历,允许重复使用当前硬币。 - 举例推导:
coins = [1, 3, 4]、amount = 6,处理完所有硬币后:
金额 j | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
dp[j] | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
答案为 2,对应 3 + 3。题目示例 coins = [1, 2, 5]、amount = 11 则需要 3 枚硬币:5 + 5 + 1。
#include <climits>
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int coin : coins) {
for (int j = coin; j <= amount; ++j) {
if (dp[j - coin] != INT_MAX) {
dp[j] = min(dp[j], dp[j - coin] + 1);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};#include <climits>
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int coin : coins) {
for (int j = coin; j <= amount; ++j) {
if (dp[j - coin] != INT_MAX) {
dp[j] = min(dp[j], dp[j - coin] + 1);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};不可达状态不能直接加一
INT_MAX只是不可达标记,不能直接计算INT_MAX + 1,否则会发生有符号整数溢出。转移前必须检查来源是否可达。amount == 0时返回0;例如只有面额2、目标金额为3时,最终仍不可达,返回-1。
求最少数量,不受组合与排列的重复计数影响
本题可以采用“硬币在外、金额正序”,也可以采用“金额递增在外、枚举硬币在内”。两者都能找到最少数量,因为相同硬币集合的不同顺序不会改变硬币数,重复候选也不会改变
min的结果;但这不代表容量可以任意倒序。
不能默认优先使用最大面额
例如面额为
[1, 3, 4]、目标为6,先用最大面额会得到4 + 1 + 1,需要3枚;最优解却是3 + 3,只需2枚。任意面额集合不一定满足这种贪心策略。
- 时间复杂度:,其中 为硬币种类数、 为目标金额
- 空间复杂度:
二十、完全平方数
题目:279. 完全平方数
求最少使用多少个正完全平方数,使它们的和恰好等于 n。例如 12 = 4 + 4 + 4,答案为 3;13 = 4 + 9,答案为 2。
可以把不超过 n 的正完全平方数 1, 4, 9, ... 看成物品,每种都能重复使用,目标是在恰好凑出 n 的前提下,使物品数量最少,与上一题的模型一致。
按照动态规划五步分析:
- 状态含义:
dp[i]表示和恰好为i的正完全平方数的最少数量。 - 递推公式:枚举一个不超过
i的平方数root * root,则dp[i] = min(dp[i], dp[i - root * root] + 1)。 - 初始化:
dp[0] = 0,表示不使用任何数;其余状态设为INT_MAX,作为求最小值的初始上界。 - 遍历顺序:外层目标和
i从1递增到n,内层枚举满足root * root <= i的正整数root。所有依赖的状态都比i小,已经求出。 - 举例推导:计算
dp[12]时,可选平方数为1、4、9:
| 选择的平方数 | 候选数量 |
|---|---|
1 | dp[11] + 1 = 3 + 1 = 4 |
4 | dp[8] + 1 = 2 + 1 = 3 |
9 | dp[3] + 1 = 3 + 1 = 4 |
因此 dp[12] = 3,对应 4 + 4 + 4。
#include <climits>
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int root = 1; root * root <= i; ++root) {
dp[i] = min(dp[i], dp[i - root * root] + 1);
}
}
return dp[n];
}
};#include <climits>
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int root = 1; root * root <= i; ++root) {
dp[i] = min(dp[i], dp[i - root * root] + 1);
}
}
return dp[n];
}
};为什么这里不需要额外判断不可达
正完全平方数包含
1,因此任何非负整数都可以由若干个1凑出。按目标和递增计算时,所有更小状态都已有有限值,不会拿INT_MAX直接加一。若换成不包含1的任意候选集合,就应像零钱兑换一样检查可达性。
与计数背包的初始化区别:
| 目标 | 空目标的状态 | 其他状态初值 | 典型转移 |
|---|---|---|---|
| 求最少数量 | dp[0] = 0,不需要物品 | INT_MAX,表示不可达或尚未求出 | min(dp[i], dp[i - value] + 1) |
| 求方案数 | dp[0] = 1,一种空方案 | 0,尚无方案 | dp[i] += dp[i - value] |
- 时间复杂度:
- 空间复杂度:
2026-10-22(周四)
动态规划(十一)
二十一、单词拆分
题目:139. 单词拆分
判断字符串 s 能否拆分为字典 wordDict 中的一个或多个单词,字典中的单词可以重复使用。
可以类比完全背包:单词是可重复使用的物品,字符串是要恰好拼出的目标。但这里不只是凑出相同长度,还必须按原字符串的顺序匹配字符。
按照动态规划五步分析:
- 状态含义:
dp[i]表示字符串前缀s[0, i)能否由字典单词拼成,即前i个字符是否可拆分。 - 递推公式:枚举最后一个单词的起点
j,若dp[j] == true,且子串s[j, i)在字典中,则dp[i] = true。这里的区间都是左闭右开,对应s.substr(j, i - j)。 - 初始化:
dp[0] = true,表示空前缀可以作为拼接的起点;其余状态设为false,表示尚未找到合法拆分。 - 遍历顺序:外层前缀长度
i从1递增到字符串长度,内层枚举0 <= j < i的切分点,保证更短前缀的状态已求出。 - 举例推导:
s = "leetcode"、wordDict = ["leet", "code"]:dp[0] = true。i = 4、j = 0时,"leet"在字典中,因此dp[4] = true。i = 8、j = 4时,前缀"leet"可拆分,且"code"在字典中,因此dp[8] = true。
用哈希集合查询单词,找到一种合法拆分后即可结束当前前缀的枚举:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
int length = static_cast<int>(s.size());
vector<bool> dp(length + 1, false);
dp[0] = true;
for (int i = 1; i <= length; ++i) {
for (int j = 0; j < i; ++j) {
if (!dp[j]) {
continue;
}
string word = s.substr(j, i - j);
if (wordSet.find(word) != wordSet.end()) {
dp[i] = true;
break;
}
}
}
return dp[length];
}
};class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
int length = static_cast<int>(s.size());
vector<bool> dp(length + 1, false);
dp[0] = true;
for (int i = 1; i <= length; ++i) {
for (int j = 0; j < i; ++j) {
if (!dp[j]) {
continue;
}
string word = s.substr(j, i - j);
if (wordSet.find(word) != wordSet.end()) {
dp[i] = true;
break;
}
}
}
return dp[length];
}
};强调拼接顺序,但不是求排列数
本题只判断是否存在合法拆分,返回布尔值,不统计方案数量。与组合总和 IV一样需要考虑顺序,但不能因此把状态写成“排列个数”。例如字典只有
"ab"时,不能因为长度相同就认为字符串"ba"可拆分。
substr的第二个参数是长度
s.substr(j, i - j)截取的是下标j到i - 1的字符,不包含下标i。dp[j]对应前面的j个字符,二者刚好拼成前i个字符。
- 时间复杂度:在哈希查找平均情况下,上述实现为 ; 为字典总字符数, 为字符串长度。两层循环有 个候选,创建子串和计算其哈希还需要与子串长度成正比的时间
- 空间复杂度:,包括哈希集合、前缀状态和临时子串
二十二、多重背包理论基础
参考题目:卡码网 56. 携带矿石资源
有 n 种物品,背包容量为 bagWeight。第 i 种物品的重量为 weight[i]、价值为 value[i],最多有 count[i] 件,求总重量不超过容量时的最大总价值。
与 0-1 背包、完全背包的区别在于每种物品有明确的数量上限。把每一件可用物品展开,都视为一件只能选择一次的物品,就能转化为 0-1 背包;也可以像下面这样直接枚举当前种类选多少件。
按照动态规划五步分析:
- 状态含义:处理完当前物品种类后,
dp[j]表示总重量不超过容量j时,能够获得的最大总价值。 - 递推公式:对于第
i种物品,枚举选择件数k,满足0 <= k <= count[i]且k * weight[i] <= j。候选价值为上一轮的dp[j - k * weight[i]] + k * value[i],在所有候选中取最大值。 - 初始化:全部设为
0,表示尚未选择任何物品时最大价值为0。循环前保留的dp[j]对应选0件,因此内层只需从k = 1开始。 - 遍历顺序:外层遍历物品种类,中层容量从大到小,内层枚举件数。容量倒序使更小容量仍保留上一轮状态,避免同一种物品累计使用超过上限。
- 举例推导:只有一种重量为
2、价值为3的物品,最多选2件,背包容量为6时:
容量 j | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
dp[j] | 0 | 0 | 3 | 3 | 6 | 6 | 6 |
容量为 6 也不能选三件,因为数量上限为 2。参考题目的示例容量为 10 时,选择两件重量为 1、价值为 15 的矿石,以及两件重量为 4、价值为 30 的矿石,总价值为 90。
输入与输出:
- 第一行是背包容量、物品种类数,注意顺序。
- 接下来三行分别给出各物品的重量、价值和数量上限。
- 输出能够获得的最大总价值。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int bagWeight, n;
if (!(cin >> bagWeight >> n)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
vector<int> count(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
for (int i = 0; i < n; ++i) {
cin >> count[i];
}
vector<int> dp(bagWeight + 1, 0);
for (int i = 0; i < n; ++i) {
for (int j = bagWeight; j >= weight[i]; --j) {
int maxCount = min(count[i], j / weight[i]);
for (int k = 1; k <= maxCount; ++k) {
dp[j] = max(
dp[j],
dp[j - k * weight[i]] + k * value[i]
);
}
}
}
cout << dp[bagWeight] << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int bagWeight, n;
if (!(cin >> bagWeight >> n)) {
return 0;
}
vector<int> weight(n);
vector<int> value(n);
vector<int> count(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
for (int i = 0; i < n; ++i) {
cin >> count[i];
}
vector<int> dp(bagWeight + 1, 0);
for (int i = 0; i < n; ++i) {
for (int j = bagWeight; j >= weight[i]; --j) {
int maxCount = min(count[i], j / weight[i]);
for (int k = 1; k <= maxCount; ++k) {
dp[j] = max(
dp[j],
dp[j - k * weight[i]] + k * value[i]
);
}
}
}
cout << dp[bagWeight] << '\n';
return 0;
}枚举件数时,来源仍须是上一轮状态
当容量
j倒序遍历时,j - k * weight[i]比j小,尚未被当前种类更新。如果改成容量正序,来源可能已经用过当前物品,再额外加上k件,就可能突破count[i]的限制。
数量较大时可以优化
逐件展开会产生很多 0-1 物品,直接枚举件数也可能较慢。后续可学习二进制拆分,把每种物品分成若干组,再按 0-1 背包处理。
- 时间复杂度: 的上界,其中 为容量、 为各物品数量上限的最大值;实际还受
j / weight[i]限制 - 空间复杂度:DP 数组为 ,连同物品信息为
2026-10-23(周五)
动态规划(十二)
二十三、打家劫舍
题目:198. 打家劫舍
房屋沿街排成一行,每间房屋中有非负金额 nums[i]。不能同时偷相邻的两间房屋,求能偷到的最大总金额。
按照动态规划五步分析:
- 状态含义:
dp[i]表示只考虑下标[0, i]的房屋,在不偷相邻房屋的前提下,能够获得的最大金额。 - 递推公式:对第
i间房屋比较偷与不偷:- 偷当前房屋:不能偷第
i - 1间,候选为dp[i - 2] + nums[i]。 - 不偷当前房屋:候选为
dp[i - 1]。 - 因此,
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]),适用于i >= 2。
- 偷当前房屋:不能偷第
- 初始化:
dp[0] = nums[0],dp[1] = max(nums[0], nums[1])。只有一间房屋时直接返回其金额;代码也额外处理空数组。 - 遍历顺序:下标从
2开始递增,因为当前状态依赖前一个和前两个状态。 - 举例推导:
nums = [2, 7, 9, 3, 1]:
房屋下标 i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
nums[i] | 2 | 7 | 9 | 3 | 1 |
dp[i] | 2 | 7 | 11 | 11 | 12 |
最终答案为 12,选择下标 0、2、4 的房屋,即 2 + 9 + 1。
class Solution {
public:
int rob(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
vector<int> dp(n, 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i) {
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[n - 1];
}
};class Solution {
public:
int rob(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
vector<int> dp(n, 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i) {
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[n - 1];
}
};考虑第
i间,不代表必须偷第i间
dp[i]是整个前缀范围内的最优金额,当前房屋可以偷,也可以不偷。不能直接把“偷当前房屋”的候选当成最终状态。
- 时间复杂度:
- 空间复杂度:;只保留前两个状态,可优化为
二十四、打家劫舍 II
题目:213. 打家劫舍 II
房屋改为围成一圈,除了原有的相邻约束,第一间和最后一间也相邻,不能同时偷。
环形转线性的思路:
当房屋至少有两间时,任何合法方案都至少放弃首尾中的一间,因此分别求两个闭区间的线性最优解:
- 排除最后一间:只考虑
[0, n - 2]。 - 排除第一间:只考虑
[1, n - 1]。 - 取两个结果的最大值。首尾都不偷的方案已经包含在这两个范围内,无须再单独计算。
范围里包含首间,不等于必须偷首间
[0, n - 2]只是允许考虑第一间,不强制选择它;[1, n - 1]同理。更准确的表述是“排除尾部”与“排除首部”,而不是“必须包含首部”与“必须包含尾部”。
对每个线性区间 [start, end],继续按照动态规划五步分析:
- 状态含义:
dp[i]表示只考虑下标[start, i]的房屋,能够获得的最大合法金额。 - 递推公式:
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]),与上一题相同。 - 初始化:
dp[start] = nums[start],dp[start + 1] = max(nums[start], nums[start + 1]);如果区间只有一间,直接返回该房屋金额。 - 遍历顺序:从
start + 2递增到end,包含右端点。 - 举例推导:
nums = [1, 2, 3, 1]:
| 计算范围 | 可考虑的房屋金额 | 线性最优值 |
|---|---|---|
[0, 2] | [1, 2, 3] | 4,选择 1 + 3 |
[1, 3] | [2, 3, 1] | 3,选择 3 或 2 + 1 |
最终答案为 max(4, 3) = 4。若 nums = [2, 3, 2],则答案为 3,不能同时选择首尾的两个 2。
class Solution {
private:
// 在闭区间 [start, end] 内求线性房屋的最优解。
int robRange(const vector<int>& nums, int start, int end) {
if (start == end) {
return nums[start];
}
vector<int> dp(nums.size(), 0);
dp[start] = nums[start];
dp[start + 1] = max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; ++i) {
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[end];
}
public:
int rob(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
int withoutLast = robRange(nums, 0, n - 2);
int withoutFirst = robRange(nums, 1, n - 1);
return max(withoutLast, withoutFirst);
}
};class Solution {
private:
// 在闭区间 [start, end] 内求线性房屋的最优解。
int robRange(const vector<int>& nums, int start, int end) {
if (start == end) {
return nums[start];
}
vector<int> dp(nums.size(), 0);
dp[start] = nums[start];
dp[start + 1] = max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; ++i) {
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[end];
}
public:
int rob(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
int withoutLast = robRange(nums, 0, n - 2);
int withoutFirst = robRange(nums, 1, n - 1);
return max(withoutLast, withoutFirst);
}
};一间和两间房屋的边界
只有一间时直接取该房屋金额,不能套用两个区间拆分;只有两间时,两个区间各只有一间,最终取两者最大值。两次线性计算只把时间常数翻倍,复杂度仍是 。
- 时间复杂度:
- 空间复杂度:;将区间内的递推改为滚动状态,可优化为
2026-10-24(周六)
动态规划(十三)
二十五、打家劫舍 III
房屋之间的关系是一棵二叉树,直接相连的父子节点不能同时偷,求能够获得的最大金额。这次不再按数组下标递推,而是先求左右子树,再合并当前节点的状态,属于树形动态规划。
按照动态规划五步分析:
- 状态含义:每个节点返回长度为
2的数组,表示以该节点为根的整棵子树的最优金额:state[0]:不偷当前节点时的最大金额。state[1]:偷当前节点时的最大金额。
- 递推公式:设左右子树返回
left和right:- 偷当前节点,两个直接孩子都不能偷:
steal = node->val + left[0] + right[0]。 - 不偷当前节点,左右孩子分别选偷与不偷中的较优值:
skip = max(left[0], left[1]) + max(right[0], right[1])。 - 返回
{skip, steal},保持下标含义一致。
- 偷当前节点,两个直接孩子都不能偷:
- 初始化:空节点返回
{0, 0},表示没有房屋时,两种状态的贡献都为0。 - 遍历顺序:采用后序遍历(左、右、中),先得到左右孩子的状态,才能计算当前节点。
- 举例推导:树的层序表示为
[3, 2, 3, null, 3, null, 1],根的两个孩子各有一个右孩子:
| 节点位置与金额 | 不偷当前节点 | 偷当前节点 |
|---|---|---|
左子树的叶子 3 | 0 | 3 |
右子树的叶子 1 | 0 | 1 |
根的左孩子 2 | 3 | 2 |
根的右孩子 3 | 1 | 3 |
根节点 3 | max(3, 2) + max(1, 3) = 6 | 3 + 3 + 1 = 7 |
最终取根节点两种状态的最大值,答案为 7。
class Solution {
private:
// 返回值:下标 0 为不偷当前节点,下标 1 为偷当前节点。
vector<int> robTree(TreeNode* node) {
if (node == nullptr) {
return {0, 0};
}
vector<int> left = robTree(node->left);
vector<int> right = robTree(node->right);
int steal = node->val + left[0] + right[0];
int skip = max(left[0], left[1]) + max(right[0], right[1]);
return {skip, steal};
}
public:
int rob(TreeNode* root) {
vector<int> result = robTree(root);
return max(result[0], result[1]);
}
};class Solution {
private:
// 返回值:下标 0 为不偷当前节点,下标 1 为偷当前节点。
vector<int> robTree(TreeNode* node) {
if (node == nullptr) {
return {0, 0};
}
vector<int> left = robTree(node->left);
vector<int> right = robTree(node->right);
int steal = node->val + left[0] + right[0];
int skip = max(left[0], left[1]) + max(right[0], right[1]);
return {skip, steal};
}
public:
int rob(TreeNode* root) {
vector<int> result = robTree(root);
return max(result[0], result[1]);
}
};不偷当前节点,不代表一定偷孩子
左右孩子可以各自选择更优状态,两者之间没有直接相邻约束。因此需要分别取
max,不能直接写成left[1] + right[1]。同样,偷当前节点只是禁止偷直接孩子,并不会禁止偷更深层的合法节点。
- 时间复杂度:,每个节点只计算一次
- 空间复杂度:,其中 为树高,用于递归栈及每层的常数大小状态;树退化为链时为
二十六、买卖股票的最佳时机
给定每天的股票价格 prices,最多完成一次买入、一次卖出,且必须先买后卖,求最大利润。如果无法获利,可以不交易,返回 0。
按照动态规划五步分析:
- 状态含义:以初始现金为
0,记录第i天结束时的两种状态:dp[i][0]:持有一股股票时的最大现金净额,已经扣除买入成本,不把手中股票按市值计入现金。dp[i][1]:不持有股票时的最大现金净额,可以来自没有交易或已经卖出。
- 递推公式:
- 持有股票:昨天就持有,或今天作为唯一一次买入,
dp[i][0] = max(dp[i - 1][0], -prices[i])。 - 不持有股票:昨天就不持有,或今天卖出昨天持有的股票,
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])。
- 持有股票:昨天就持有,或今天作为唯一一次买入,
- 初始化:
dp[0][0] = -prices[0],表示第一天买入;dp[0][1] = 0,表示第一天不交易。代码额外处理空数组。 - 遍历顺序:日期从第
1天递增,使用前一天的状态推导当天状态。 - 举例推导:
prices = [7, 1, 5, 3, 6, 4],日期下标从0开始:
日期 i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 价格 | 7 | 1 | 5 | 3 | 6 | 4 |
持有 dp[i][0] | -7 | -1 | -1 | -1 | -1 | -1 |
不持有 dp[i][1] | 0 | 0 | 4 | 4 | 5 | 5 |
最终答案是最后一天不持有股票的状态,即 5,对应价格 1 买入、价格 6 卖出。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], -prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
};class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], -prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
};单次交易买入时,不能继承卖出后的利润
本题今天买入的候选是
-prices[i],而不是dp[i - 1][1] - prices[i]。后者可能把已经卖出的利润用于再次买入,变成允许多次交易的模型;不要与买卖股票的最佳时机 II混淆。
不交易也是合法选择
不持有状态初始化为
0,所以价格持续下降时最终返回0,不会被迫接受负利润。只有一天时也返回0。
- 时间复杂度:
- 空间复杂度:;只保存前一天的两个状态,可优化为
2026-10-25(周日)
动态规划(十四)
二十七、买卖股票的最佳时机 II
可以多次买入和卖出,但任何时候最多持有一股股票,必须卖出后才能再次买入。与单次交易版本相比,关键变化是买入时可以使用此前卖出后积累的利润。
按照动态规划五步分析:
- 状态含义:以初始现金为
0,记录第i天结束时的最大现金净额:dp[i][0]:持有一股股票,已经扣除买入成本,不将手中股票按市值计入现金。dp[i][1]:不持有股票,可以来自未交易或已经完成若干次交易。
- 递推公式:
- 持有:昨天就持有,或今天用昨天不持有时的现金买入,
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])。 - 不持有:昨天就不持有,或今天卖出昨天持有的股票,
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])。
- 持有:昨天就持有,或今天用昨天不持有时的现金买入,
- 初始化:
dp[0][0] = -prices[0],dp[0][1] = 0,分别对应第一天买入与不交易。代码额外处理空数组。 - 遍历顺序:日期从第
1天开始递增,读取前一天的两个状态。 - 举例推导:
prices = [7, 1, 5, 3, 6, 4]:
| 日期下标 | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 价格 | 7 | 1 | 5 | 3 | 6 | 4 |
持有 dp[i][0] | -7 | -1 | -1 | 1 | 1 | 3 |
不持有 dp[i][1] | 0 | 0 | 4 | 4 | 7 | 7 |
答案为 7,对应价格 1 买入、5 卖出,再以 3 买入、6 卖出,总利润为 4 + 3。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
};class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
};买入状态体现交易次数的区别
单次交易版本的买入候选是
-prices[i];本题是dp[i - 1][1] - prices[i],允许此前获利后再次买入。持有状态的现金净额也可能为正,例如先赚到4,再以3买入,现金净额为1。
与贪心解法对应
本题也可以累加相邻两天的所有正价差,见贪心算法中的股票 II。这里保留动态规划状态,便于后续加入交易次数等限制。
- 时间复杂度:
- 空间复杂度:;只保留前一天的两个状态,可优化为
二十八、买卖股票的最佳时机 III
最多完成两笔交易,每笔交易包含一次买入和一次卖出,不能同时持有多股。也可以只交易一次或完全不交易。
按照动态规划五步分析:
-
状态含义:
dp[i][j]表示第i天结束时,处于交易阶段j的最大现金净额:状态 j含义 0始终未交易,现金为 01第一次持有阶段,最多允许一次买入 2最多完成一笔交易,且当前不持有股票 3第二次持有阶段,在两次买入的预算内持有股票 4最多完成两笔交易,且当前不持有股票 -
递推公式:每个阶段都可以延续昨天的状态,或由前一阶段进行一次买卖转移:
dp[i][0] = 0。dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i])。dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i])。dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i])。dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i])。
-
初始化:第
0天,dp[0][0] = dp[0][2] = dp[0][4] = 0,dp[0][1] = dp[0][3] = -prices[0]。这些是允许少做交易的状态,不是要求当天真实完成两次买卖。 -
遍历顺序:日期递增。下面将日期维度压缩,只保留
5个状态;每天按4 → 3 → 2 → 1倒序更新,使右侧来源仍是前一天的值。 -
举例推导:
prices = [3, 3, 5, 0, 0, 3, 1, 4],部分关键日期的状态如下:
| 日期下标与价格 | dp[1] | dp[2] | dp[3] | dp[4] |
|---|---|---|---|---|
| 第 0 天,价格 3 | -3 | 0 | -3 | 0 |
| 第 2 天,价格 5 | -3 | 2 | -3 | 2 |
| 第 3 天,价格 0 | 0 | 2 | 2 | 2 |
| 第 5 天,价格 3 | 0 | 3 | 2 | 5 |
| 第 7 天,价格 4 | 0 | 4 | 2 | 6 |
答案为 6,例如价格 0 买入、3 卖出,再以 1 买入、4 卖出,两笔各获利 3。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<int> dp(5, 0);
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < n; ++i) {
// 倒序更新,确保转移读取的仍是前一天的状态。
dp[4] = max(dp[4], dp[3] + prices[i]);
dp[3] = max(dp[3], dp[2] - prices[i]);
dp[2] = max(dp[2], dp[1] + prices[i]);
dp[1] = max(dp[1], dp[0] - prices[i]);
}
return dp[4];
}
};class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<int> dp(5, 0);
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < n; ++i) {
// 倒序更新,确保转移读取的仍是前一天的状态。
dp[4] = max(dp[4], dp[3] + prices[i]);
dp[3] = max(dp[3], dp[2] - prices[i]);
dp[2] = max(dp[2], dp[1] + prices[i]);
dp[1] = max(dp[1], dp[0] - prices[i]);
}
return dp[4];
}
};“第二次”是交易阶段,不是强制交易两次
dp[2]、dp[4]都允许不交易,所以初值为0;只有一次买入的路径也应允许放在两次交易预算的持有状态中,因此dp[3]初始化为-prices[0]。这不表示第一天必须实际完成第一次交易再第二次买入。
原地更新要明确读的是哪一天
原笔记的
1 → 2 → 3 → 4正序更新会使用当天刚更新的状态,相当于允许同日进行不增加利润的买卖;在本题无手续费、无冷冻期的条件下也能得到正确最优值。这里改用倒序,是为了与“全部读取昨天状态”的递推公式严格一致,不能将更新顺序机械套用于其他股票题。
- 时间复杂度:
- 空间复杂度:,仅保存固定的
5个状态
2026-10-27(周二)
动态规划(十六)
三十一、买卖股票的最佳时机含手续费
可以买卖多次,但最多持有一股股票,每完成一笔买入、卖出的交易,需要支付一次手续费 fee。在不限交易次数的股票题基础上,增加手续费即可;下面统一在卖出时扣费。
按照动态规划五步分析:
- 状态含义:
dp[i][0]表示第i天结束时持有一股股票的最大现金净额,dp[i][1]表示不持有股票的最大现金净额。 - 递推公式:
- 持有:继续持有,或今天买入,
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])。 - 不持有:继续空仓,或今天卖出并扣除手续费,
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee)。
- 持有:继续持有,或今天买入,
- 初始化:
dp[0][0] = -prices[0]、dp[0][1] = 0。因为约定卖出时扣费,第一天买入不额外扣手续费。代码额外处理空数组。 - 遍历顺序:日期递增,当天两个状态都读取前一天的值。
- 举例推导:
prices = [1, 3, 2, 8, 4, 9]、fee = 2:
| 日期下标 | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 价格 | 1 | 3 | 2 | 8 | 4 | 9 |
持有 dp[i][0] | -1 | -1 | -1 | -1 | 1 | 1 |
不持有 dp[i][1] | 0 | 0 | 0 | 5 | 5 | 8 |
最终答案为 8,对应两笔交易:(8 - 1 - 2) + (9 - 4 - 2) = 8。
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
return dp[n - 1][1];
}
};class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = static_cast<int>(prices.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
return dp[n - 1][1];
}
};每笔交易只扣一次手续费
这里统一在卖出时扣费,买入时不再扣。手续费也可以改在买入时扣除,但初始化和递推必须一起调整,不能买入、卖出各扣一次。最终返回不持有股票的状态,与已完成交易的利润含义一致。
- 时间复杂度:
- 空间复杂度:;只保留前一天的两个状态,可优化为
三十二、最长递增子序列
题目:300. 最长递增子序列
求数组中最长严格递增子序列的长度。子序列可以跳过元素,但必须保持原有的下标顺序;相等的元素不能延长严格递增序列。
按照动态规划五步分析:
- 状态含义:
dp[i]表示在下标[0, i]范围内,必须以nums[i]结尾的最长严格递增子序列长度。 - 递推公式:枚举所有
j < i,当nums[j] < nums[i]时,可以把当前元素接在以nums[j]结尾的序列之后,更新dp[i] = max(dp[i], dp[j] + 1)。 - 初始化:每个
dp[i]都设为1,因为单个元素本身就是长度为1的递增子序列;空数组返回0。 - 遍历顺序:外层下标
i递增,内层检查所有更早的下标j,保证候选状态已求出。 - 举例推导:
nums = [10, 9, 2, 5, 3, 7, 101, 18]:
下标 i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
nums[i] | 10 | 9 | 2 | 5 | 3 | 7 | 101 | 18 |
dp[i] | 1 | 1 | 1 | 2 | 2 | 3 | 4 | 4 |
所有结尾状态中的最大值为 4,例如子序列 [2, 3, 7, 101]。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n <= 1) {
return n;
}
vector<int> dp(n, 1);
int result = 1;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
result = max(result, dp[i]);
}
return result;
}
};class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n <= 1) {
return n;
}
vector<int> dp(n, 1);
int result = 1;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
result = max(result, dp[i]);
}
return result;
}
};答案不一定在最后一个元素处结束
dp[i]只表示“以当前位置结尾”的最优长度,最终必须取所有dp[i]的最大值。例如[1, 2, 3, 0]的答案为3,但最后一个状态只有1。也不能先排序再求解,因为排序会改变原始下标顺序。
- 时间复杂度:
- 空间复杂度:
三十三、最长连续递增序列
求数组中最长连续且严格递增的片段长度。与上一题最大的区别是必须连续,不能跳过中间元素,因此只需要检查当前元素与前一个元素。
按照动态规划五步分析:
- 状态含义:
dp[i]表示以nums[i]结尾的最长连续严格递增片段长度。 - 递推公式:
- 若
nums[i] > nums[i - 1],则dp[i] = dp[i - 1] + 1。 - 否则连续递增中断,
dp[i] = 1,从当前元素重新开始。
- 若
- 初始化:全部设为
1;非空数组的答案至少为1,空数组返回0。 - 遍历顺序:从左到右,每个状态只依赖紧邻的前一个状态,并维护全局最大值。
- 举例推导:
nums = [1, 3, 5, 4, 7]:
下标 i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
nums[i] | 1 | 3 | 5 | 4 | 7 |
dp[i] | 1 | 2 | 3 | 1 | 2 |
最长连续片段为 [1, 3, 5],长度为 3;若允许跳过元素,则 LIS 可以取 [1, 3, 5, 7],长度为 4。
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
vector<int> dp(n, 1);
int result = 1;
for (int i = 1; i < n; ++i) {
if (nums[i] > nums[i - 1]) {
dp[i] = dp[i - 1] + 1;
}
result = max(result, dp[i]);
}
return result;
}
};class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
vector<int> dp(n, 1);
int result = 1;
for (int i = 1; i < n; ++i) {
if (nums[i] > nums[i - 1]) {
dp[i] = dp[i - 1] + 1;
}
result = max(result, dp[i]);
}
return result;
}
};相等或下降时都要重新开始
严格递增使用
>,不是>=。当连续性中断时,上述代码依靠dp[i]初始为1自动重新计数,不能继承前一个状态的长度。
两类递增序列的区别:
| 对比项 | 最长递增子序列(LIS) | 最长连续递增序列(LCIS) |
|---|---|---|
| 能否跳过中间元素 | 可以,保持相对顺序即可 | 不可以,必须下标连续 |
| 当前状态的来源 | 所有满足条件的更早位置 j < i | 仅紧邻位置 i - 1 |
| 当前实现的时间复杂度 | ||
| 相等元素能否延长 | 不能 | 不能 |
- 时间复杂度:
- 空间复杂度:;只记录当前连续长度和历史最大值,可优化为
2026-10-28(周三)
动态规划(十七)
三十四、最长重复子数组
题目:718. 最长重复子数组
给定两个整数数组,求同时出现在两个数组中的最长子数组长度。这里的“重复”指两个数组间的公共片段,在两个数组中都必须连续,不是求某个数组内部重复的片段。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示分别以nums1[i - 1]和nums2[j - 1]结尾的最长公共连续片段长度。i、j从1开始,额外一行、一列用于表示空前缀。 - 递推公式:
- 若
nums1[i - 1] == nums2[j - 1],可以同时延长前一个公共连续片段:dp[i][j] = dp[i - 1][j - 1] + 1。 - 否则连续匹配中断,
dp[i][j] = 0,不能从上方或左方继承长度。
- 若
- 初始化:
dp[i][0] = dp[0][j] = 0,空前缀没有公共元素;代码将整个表初始化为0,因此不匹配的位置无需额外赋值。 - 遍历顺序:外层
i、内层j均从小到大,保证左上角状态已计算;同时维护整个表中的最大值。 - 举例推导:
nums1 = [1, 2, 3, 2, 1]、nums2 = [3, 2, 1, 4, 7],公共片段[3, 2, 1]对应连续的左上角转移:dp[3][1] = 1→dp[4][2] = 2→dp[5][3] = 3,答案为3。
class Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
int result = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
result = max(result, dp[i][j]);
}
}
return result;
}
};class Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
int result = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
result = max(result, dp[i][j]);
}
}
return result;
}
};“以当前位置结尾”不等于“整个前缀中的最优答案”
结尾元素不相等时,当前连续片段的长度必须归零。最优片段可能在任意位置结束,因此返回整个表的最大值,而不是
dp[m][n]。上面的示例中,最后两个元素1、7不相等,dp[5][5] = 0,但答案仍为3。
- 时间复杂度:
- 空间复杂度:;其中
m、n分别为两个数组的长度
三十五、最长公共子序列
求两个字符串的最长公共子序列长度。子序列可以跳过字符,但不能改变相对顺序,不要求连续;没有公共字符时返回 0。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示text1的前i个字符(下标[0, i - 1])与text2的前j个字符(下标[0, j - 1])的最长公共子序列长度。状态是两个前缀的最优值,不要求包含两个前缀的最后一个字符。 - 递推公式:
- 若
text1[i - 1] == text2[j - 1],将这个共同字符接到两个更短前缀的公共子序列后面:dp[i][j] = dp[i - 1][j - 1] + 1。 - 否则两个末尾字符不能互相匹配,至少舍去其中一个:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])。
- 若
- 初始化:
dp[i][0] = dp[0][j] = 0,任意字符串与空串的最长公共子序列长度都是0。 - 遍历顺序:
i、j从1开始递增,所需的左上、上方和左方状态均已求出。 - 举例推导:
text1 = "abcde"、text2 = "ace",状态表如下。最终dp[5][3] = 3,对应公共子序列"ace"。
text1 前缀 / text2 前缀 | 空串 | a | ac | ace |
|---|---|---|---|---|
| 空串 | 0 | 0 | 0 | 0 |
| a | 0 | 1 | 1 | 1 |
| ab | 0 | 1 | 1 | 1 |
| abc | 0 | 1 | 2 | 2 |
| abcd | 0 | 1 | 2 | 2 |
| abcde | 0 | 1 | 2 | 3 |
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = static_cast<int>(text1.size());
int n = static_cast<int>(text2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = static_cast<int>(text1.size());
int n = static_cast<int>(text2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};长度、下标与状态范围要分清
i、j表示前缀长度,不是当前字符的下标,因此访问字符时要减1。[0, i - 1]是长度为i的下标范围,不应写成“长度为[0, i - 1]”。本题状态已包含整个前缀内的最优值,最终直接返回dp[m][n]。
- 时间复杂度:
- 空间复杂度:;其中
m、n分别为两个字符串的长度
三十六、不相交的线
题目:1035. 不相交的线
在两条水平线上依次写出两个整数数组,只能连接值相同的元素,每个元素最多参与一条连线,所有连线不能相交。求最多能画多少条线。
建模关键:将连线按第一个数组的下标从小到大排列,若它们在第二个数组中的下标也严格递增,连线就不会相交;反之,下标顺序颠倒就会产生交叉。因此,合法连线恰好对应两个数组中保持相对顺序、且每个位置只使用一次的公共子序列,本题就是整数数组版的最长公共子序列。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示nums1前i个元素与nums2前j个元素之间,最多能画出的不相交连线数。 - 递推公式:
- 若
nums1[i - 1] == nums2[j - 1],可以连接这两个末尾元素:dp[i][j] = dp[i - 1][j - 1] + 1。 - 否则舍去其中一个末尾元素:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])。
- 若
- 初始化:
dp[i][0] = dp[0][j] = 0,任意一侧为空时无法连线。 - 遍历顺序:两个前缀长度均递增,与最长公共子序列相同。
- 举例推导:
nums1 = [1, 4, 2]、nums2 = [1, 2, 4]。可以连接两个1,再连接两个4(或两个2),共2条线;若同时连接4和2,它们的下标顺序相反,会发生交叉。
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};不是求共同元素的个数,也不能先排序
仅统计两个数组共同拥有的数字,会忽略下标顺序和元素的使用次数。排序会改变原始位置关系,也会改变哪些连线相交。相同数值可以出现多次,但每个具体位置最多匹配一次。
- 时间复杂度:
- 空间复杂度:;其中
m、n分别为两个数组的长度
三道题的状态对比:
| 对比项 | 最长重复子数组 | 最长公共子序列 / 不相交的线 |
|---|---|---|
| 是否要求连续 | 两侧都要求连续 | 两侧都允许跳过元素,但保持顺序 |
dp[i][j] 的含义 | 必须以两个当前位置结尾的公共连续片段长度 | 两个前缀中的最优公共子序列长度 |
| 末尾元素相等 | 左上角 + 1 | 左上角 + 1 |
| 末尾元素不等 | 归零,中断连续匹配 | 取上方与左方的最大值 |
| 最终答案 | 整个表中的最大值 | dp[m][n] |
2026-10-29(周四)
动态规划(十八)
三十七、最大子序和
题目:53. 最大子数组和
从整数数组中找出和最大的非空连续子数组,返回其和。这里的“子序”不能理解成可以跳过元素的子序列;子数组必须连续,也不能用空子数组的和 0 代替负数答案。
按照动态规划五步分析:
- 状态含义:
dp[i]表示必须以nums[i]结尾的最大连续子数组和,不是整个前缀中的最大和。 - 递推公式:当前位置只有两种选择:接在前一个最优连续片段之后,或从当前元素重新开始。因此
dp[i] = max(dp[i - 1] + nums[i], nums[i])。 - 初始化:
dp[0] = nums[0],全局答案也初始化为nums[0],以正确处理全负数组。题目保证数组非空,代码额外对空数组返回0。 - 遍历顺序:从左到右,每个状态只依赖前一个状态,同时维护所有结尾状态的最大值。
- 举例推导:
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
下标 i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
nums[i] | -2 | 1 | -3 | 4 | -1 | 2 | 1 | -5 | 4 |
dp[i] | -2 | 1 | -2 | 4 | 3 | 5 | 6 | 1 | 5 |
最大值为 6,对应连续子数组 [4, -1, 2, 1]。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
vector<int> dp(n, 0);
dp[0] = nums[0];
int result = dp[0];
for (int i = 1; i < n; ++i) {
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
result = max(result, dp[i]);
}
return result;
}
};class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 0) {
return 0;
}
vector<int> dp(n, 0);
dp[0] = nums[0];
int result = dp[0];
for (int i = 1; i < n; ++i) {
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
result = max(result, dp[i]);
}
return result;
}
};不能把答案初始化为 0,也不能只返回最后一个状态
例如
[-3, -1, -2]的答案为-1,而不是0;最优片段也不一定包含最后一个元素。若前一个结尾状态为负数,继续拼接只会拉低当前和,因此应从当前元素重新开始。
- 时间复杂度:
- 空间复杂度:;只保留前一个结尾状态和全局最大值,可优化为
三十八、判断子序列
题目:392. 判断子序列
判断 s 是否为 t 的子序列:允许从 t 中删除部分字符,但必须按原顺序完整匹配 s。本题只判断是否存在匹配方案,不计算最长公共子序列长度,也不计算方案数。
为避免把“匹配长度”与 LCS 的前缀最优长度混淆,这里直接使用布尔状态。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示s的前i个字符,是否为t的前j个字符的子序列。 - 递推公式:
- 若
s[i - 1] == t[j - 1],可以用当前字符完成最后一次匹配,dp[i][j] = dp[i - 1][j - 1]。若原本存在更早完成的匹配,将最后一次匹配移到当前这个相同字符也仍然合法,所以无需额外保留另一种分支。 - 否则跳过
t[j - 1],dp[i][j] = dp[i][j - 1];不能跳过s中的字符来冒充完整匹配。
- 若
- 初始化:
dp[0][j] = true,空串是任意字符串的子序列;dp[i][0] = false(i > 0),非空串不能从空串中匹配出来,且dp[0][0] = true。 - 遍历顺序:两个前缀长度从小到大,保证左上角和左方状态已经求出。
- 举例推导:
s = "abc"、t = "ahbgdc",分别匹配t中下标为0、2、5的字符,dp[1][1]、dp[2][3]、dp[3][6]依次为true;若s = "axc",由于没有字符x,无法完整匹配,结果为false。
class Solution {
public:
bool isSubsequence(string s, string t) {
int m = static_cast<int>(s.size());
int n = static_cast<int>(t.size());
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
for (int j = 0; j <= n; ++j) {
dp[0][j] = true;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = dp[i][j - 1];
}
}
}
return dp[m][n];
}
};class Solution {
public:
bool isSubsequence(string s, string t) {
int m = static_cast<int>(s.size());
int n = static_cast<int>(t.size());
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
for (int j = 0; j <= n; ++j) {
dp[0][j] = true;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = dp[i][j - 1];
}
}
}
return dp[m][n];
}
};动态规划便于理解,单次判断可用双指针
用一个指针指向
s当前待匹配字符,另一个指针从左到右扫描t;相等时推进s的指针,最后判断是否匹配完s。这种实现时间复杂度为 、额外空间为 。上面保留二维 DP,用于学习前缀状态与单侧跳过的关系。
- 时间复杂度:,包含建表与空串初始化;两串非空时可简写为
- 空间复杂度:;其中
m、n分别为s、t的长度
三十九、不同的子序列
题目:115. 不同的子序列
统计从源字符串 s 中选取若干下标、按顺序组成目标字符串 t 的方案数。下标选择不同就算不同方案,不是统计不同的结果字符串;所有被计数的结果字符串都等于 t。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示从s的前i个字符中选出子序列,恰好等于t的前j个字符的方案数。不要求必须选择s[i - 1]。 - 递推公式:
- 若
s[i - 1] == t[j - 1],分为两类互不重叠的方案:使用当前源字符匹配目标末尾,有dp[i - 1][j - 1]种;不使用当前源字符,有dp[i - 1][j]种。因此dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]。 - 否则只能跳过当前源字符,
dp[i][j] = dp[i - 1][j]。
- 若
- 初始化:
dp[i][0] = 1(0 <= i <= m),从任意源前缀组成空目标,都恰好有一种方案:一个字符也不选。dp[0][j] = 0(j > 0),空源串不能组成非空目标;特别地dp[0][0] = 1。 - 遍历顺序:源前缀长度
i、目标前缀长度j递增,当前状态仅依赖上一行。若目标前缀比源前缀更长,其方案数自然为0。 - 举例推导:
s = "babgbag"、t = "bag",最终dp[7][3] = 5:
s 前缀 / t 前缀 | 空串 | b | ba | bag |
|---|---|---|---|---|
| 空串 | 1 | 0 | 0 | 0 |
| b | 1 | 1 | 0 | 0 |
| ba | 1 | 1 | 1 | 0 |
| bab | 1 | 2 | 1 | 0 |
| babg | 1 | 2 | 1 | 1 |
| babgb | 1 | 3 | 1 | 1 |
| babgba | 1 | 3 | 4 | 1 |
| babgbag | 1 | 3 | 4 | 5 |
下面对计数采用上限截断:先转为 long long 相加,再将存储值限制在 INT_MAX 以内。
class Solution {
public:
int numDistinct(string s, string t) {
int m = static_cast<int>(s.size());
int n = static_cast<int>(t.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
long long count = static_cast<long long>(dp[i - 1][j - 1])
+ dp[i - 1][j];
dp[i][j] = static_cast<int>(
min(count, static_cast<long long>(INT_MAX))
);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m][n];
}
};class Solution {
public:
int numDistinct(string s, string t) {
int m = static_cast<int>(s.size());
int n = static_cast<int>(t.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
long long count = static_cast<long long>(dp[i - 1][j - 1])
+ dp[i - 1][j];
dp[i][j] = static_cast<int>(
min(count, static_cast<long long>(INT_MAX))
);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m][n];
}
};最终答案不溢出,不代表所有中间计数都很小
题目保证最终答案在 32 位有符号整数范围内,但某些较短目标前缀可能有极多匹配方案。例如
s、t都由1000个a组成时,最终答案为1,中间却会出现组合数 ,连 64 位整数也装不下。这里存储“真实计数与INT_MAX的较小值”。由于递推只有非负加法和复制,截断与递推相容;在题目保证下,最终结果仍然精确,不依赖无符号整数回绕。
空目标的初始化必须覆盖最后一行
dp[i][0] = 1的循环应写成i <= m,而不是i < m。虽然本题目标非空,完整初始化仍能让状态含义一致,并正确支持空目标。注意本题只能跳过源串s的字符,不能删除目标串t的字符来增加答案。
- 时间复杂度:(题目保证两串非空)
- 空间复杂度:;其中
m、n分别为s、t的长度
两道子序列匹配题的区别:
| 对比项 | 判断子序列 | 不同的子序列 |
|---|---|---|
| 任务 | 判断 s 是否能从 t 中选出 | 统计从 s 中选出 t 的方案数 |
| 源串 / 目标串 | 源串 t,目标串 s | 源串 s,目标串 t |
| 当前状态类型 | 布尔值:能否完整匹配目标前缀 | 整数:完整匹配目标前缀的方案数 |
| 字符相等时 | 只需判断能否匹配,取左上角状态即可 | 使用与不使用当前源字符的方案都要计入 |
| 目标为空 | true | 1 种方案 |
| 源为空、目标非空 | false | 0 种方案 |
2026-10-30(周五)
动态规划(十九)
四十、两个字符串的删除操作
每次可以从两个字符串中的任意一个删除一个字符,求使两串相等的最少操作次数。只能删除,不能插入或替换;如果两个末尾字符都删除,需要算两次操作。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示使word1的前i个字符与word2的前j个字符相等,所需的最少删除次数。这里i、j表示前缀长度,末尾字符的下标分别为i - 1、j - 1。 - 递推公式:
- 若
word1[i - 1] == word2[j - 1],可以保留这两个末尾字符,不增加操作:dp[i][j] = dp[i - 1][j - 1]。 - 否则至少删除一个末尾字符:删除
word1[i - 1],代价为dp[i - 1][j] + 1;或删除word2[j - 1],代价为dp[i][j - 1] + 1。取两者最小值。
- 若
- 初始化:
dp[i][0] = i、dp[0][j] = j。当一侧为空串时,必须删掉另一侧的全部字符;dp[0][0] = 0。 - 遍历顺序:两个前缀长度从小到大,保证左上、上方和左方状态均已求出。
- 举例推导:
word1 = "sea"、word2 = "eat":
word1 前缀 / word2 前缀 | 空串 | e | ea | eat |
|---|---|---|---|---|
| 空串 | 0 | 1 | 2 | 3 |
| s | 1 | 2 | 3 | 4 |
| se | 2 | 1 | 2 | 3 |
| sea | 3 | 2 | 1 | 2 |
最终 dp[3][3] = 2:从 "sea" 中删除 s,从 "eat" 中删除 t,两串都变为 "ea"。
class Solution {
public:
int minDistance(string word1, string word2) {
int m = static_cast<int>(word1.size());
int n = static_cast<int>(word2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = i;
}
for (int j = 0; j <= n; ++j) {
dp[0][j] = j;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;
}
}
}
return dp[m][n];
}
};class Solution {
public:
int minDistance(string word1, string word2) {
int m = static_cast<int>(word1.size());
int n = static_cast<int>(word2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = i;
}
for (int j = 0; j <= n; ++j) {
dp[0][j] = j;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;
}
}
}
return dp[m][n];
}
};为什么代码没有单独写“同时删除两个末尾字符”?
同时删除的候选代价是
dp[i - 1][j - 1] + 2,但它已包含在连续两次单侧删除的路径中,不会比上述两个候选更优,因此可以省略。不能将这个代价写成+ 1,否则就把“删除两个字符”误当成了一次替换。
与最长公共子序列的关系
最后保留下来的字符串一定是两串的公共子序列。要使删除次数最少,就要保留最长公共子序列。设其长度为
L,则答案为(m - L) + (n - L) = m + n - 2 * L,可联系最长公共子序列理解。
- 时间复杂度:(题目保证两串非空)
- 空间复杂度:;其中
m、n分别为两个字符串的长度,代码也支持空串
四十一、编辑距离
题目:72. 编辑距离
将 word1 转换成 word2,每次可以插入、删除或替换一个字符,求最少操作次数。为避免操作方向混淆,下面始终把 word1 视为源串、word2 视为目标串,操作均施加于源串。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示将word1的前i个字符转换为word2的前j个字符,所需的最少编辑次数。它表示两个完整前缀之间的转换代价,而不是必须修改末尾字符。 - 递推公式:
- 若
word1[i - 1] == word2[j - 1],末尾字符无需修改:dp[i][j] = dp[i - 1][j - 1]。 - 否则比较三种操作的代价,取最小值:
- 删除源串的末尾字符:
dp[i - 1][j] + 1。 - 插入目标串的末尾字符:先将源前缀转换为目标的前
j - 1个字符,再插入word2[j - 1],代价为dp[i][j - 1] + 1。 - 替换源串的末尾字符为目标的末尾字符:
dp[i - 1][j - 1] + 1。
- 删除源串的末尾字符:
- 若
- 初始化:
dp[i][0] = i,将非空源前缀变为空串需要全部删除;dp[0][j] = j,将空串变为目标前缀需要逐个插入。两串均为空时,代价为0。 - 遍历顺序:
i、j从1开始递增,当前状态依赖的左上、上方、左方状态均已求出。 - 举例推导:
word1 = "horse"、word2 = "ros":
word1 前缀 / word2 前缀 | 空串 | r | ro | ros |
|---|---|---|---|---|
| 空串 | 0 | 1 | 2 | 3 |
| h | 1 | 1 | 2 | 3 |
| ho | 2 | 2 | 1 | 2 |
| hor | 3 | 2 | 2 | 2 |
| hors | 4 | 3 | 3 | 2 |
| horse | 5 | 4 | 4 | 3 |
最终 dp[5][3] = 3。一种转换过程为:horse → rorse(替换 h 为 r)→ rose(删除多余的 r)→ ros(删除 e)。
class Solution {
public:
int minDistance(string word1, string word2) {
int m = static_cast<int>(word1.size());
int n = static_cast<int>(word2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = i;
}
for (int j = 0; j <= n; ++j) {
dp[0][j] = j;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = min({
dp[i - 1][j], // 删除
dp[i][j - 1], // 插入
dp[i - 1][j - 1] // 替换
}) + 1;
}
}
}
return dp[m][n];
}
};class Solution {
public:
int minDistance(string word1, string word2) {
int m = static_cast<int>(word1.size());
int n = static_cast<int>(word2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
dp[i][0] = i;
}
for (int j = 0; j <= n; ++j) {
dp[0][j] = j;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = min({
dp[i - 1][j], // 删除
dp[i][j - 1], // 插入
dp[i - 1][j - 1] // 替换
}) + 1;
}
}
}
return dp[m][n];
}
};替换一次,不等于删除两次
对
"a"和"b",上一题必须分别删除两个字符,答案为2;本题只需一次替换,答案为1。因此编辑距离在字符不等时要考虑左上角+ 1,也不能直接套用m + n - 2 * LCS的公式。
固定源串、目标串后再解释操作
从两串对齐的角度看,“在一侧添加字符”和“从另一侧删除对应字符”有对称关系。但推导时混用方向容易把递推项解释反:在
word1→word2的固定方向下,上方+ 1对应删除源字符,左方+ 1对应插入目标字符。
- 时间复杂度:,包含建表与初始化;两串非空时可简写为
- 空间复杂度:;其中
m、n分别为两个字符串的长度
两道字符串编辑题的区别:
| 对比项 | 两个字符串的删除操作 | 编辑距离 |
|---|---|---|
| 目标 | 从两串中删除字符,使它们相等 | 将源串 word1 转换为目标串 word2 |
| 允许操作 | 从任意一侧删除一个字符 | 对源串插入、删除、替换一个字符 |
| 末尾字符相等 | 左上角状态,不增加代价 | 左上角状态,不增加代价 |
| 末尾字符不等 | 上方、左方取最小值后 + 1 | 上方、左方、左上角取最小值后 + 1 |
| 与 LCS 的关系 | 答案等于 m + n - 2 * LCS | 一般不能套用该公式 |
"a"、"b" 的答案 | 2 | 1 |
2026-10-31(周六)
动态规划(二十)
四十二、回文子串
题目:647. 回文子串
统计字符串中回文子串的数量。子串必须连续,回文表示正读、反读相同;即使内容相同,只要起止下标不同,也分别计数,不是统计不同内容的回文字符串。
按照动态规划五步分析:
- 状态含义:布尔值
dp[i][j]表示闭区间[i, j]对应的子串是否为回文。这里i、j都是字符下标,不是前缀长度。 - 递推公式:
- 若
s[i] != s[j],首尾不等,dp[i][j] = false。 - 若
s[i] == s[j]且j - i <= 1,区间长度为1或2,直接为回文。 - 若首尾相等且区间长度大于
2,则取决于内部区间:dp[i][j] = dp[i + 1][j - 1]。 - 每得到一个为
true的区间,答案增加1。
- 若
- 初始化:整个表设为
false。单字符区间在递推时自动设为true,无需额外初始化对角线。 - 遍历顺序:左端点
i从n - 1递减到0,右端点j从i递增到n - 1。这样依赖的下方一行dp[i + 1][j - 1]已经计算过;只遍历i <= j的有效区间。 - 举例推导:
s = "aaa",三个单字符区间、两个长度为2的区间、一个长度为3的区间均为回文,总数为3 + 2 + 1 = 6。其中dp[0][2]依赖已经求出的dp[1][1]。
class Solution {
public:
int countSubstrings(string s) {
int n = static_cast<int>(s.size());
vector<vector<bool>> dp(n, vector<bool>(n, false));
int result = 0;
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
if (s[i] == s[j] && (j - i <= 1 || dp[i + 1][j - 1])) {
dp[i][j] = true;
++result;
}
}
}
return result;
}
};class Solution {
public:
int countSubstrings(string s) {
int n = static_cast<int>(s.size());
vector<vector<bool>> dp(n, vector<bool>(n, false));
int result = 0;
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
if (s[i] == s[j] && (j - i <= 1 || dp[i + 1][j - 1])) {
dp[i][j] = true;
++result;
}
}
}
return result;
}
};短区间要单独处理,计数不能只看整串
代码中
||的短路求值保证长度为1或2时不访问内部区间,避免无效下标。答案是所有回文区间的数量,不是dp[0][n - 1],也不是最长回文的长度。代码先把长度转换为int,空串时外层循环从-1开始并直接结束,返回0。
- 时间复杂度:
- 空间复杂度:
四十三、最长回文子序列
题目:516. 最长回文子序列
求字符串中最长回文子序列的长度。子序列可以跳过字符,但必须保持原有相对顺序;不要求连续,也不是统计方案数。
按照动态规划五步分析:
- 状态含义:
dp[i][j]表示原字符串在闭区间[i, j]内能选出的最长回文子序列长度,不要求必须包含两个端点。 - 递推公式:
- 若
s[i] == s[j],可以在内部区间的最优回文子序列两端加上这两个相同字符,dp[i][j] = dp[i + 1][j - 1] + 2。 - 否则两个端点不可能同时作为回文的首尾,至少舍去其中一个,
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])。
- 若
- 初始化:
dp[i][i] = 1,单个字符本身就是回文子序列;其余位置初始化为0。当长度为2且两端相等时,所读取的dp[i + 1][i] = 0表示空内部区间,所以结果为2。代码额外处理空串,返回0。 - 遍历顺序:左端点
i从大到小,右端点j从i + 1向右递增,保证下方、左方和左下方状态均可使用。 - 举例推导:
s = "bbbab",区间状态如下,—表示不参与正常区间遍历的下三角位置:
i / j | 0:b | 1:b | 2:b | 3:a | 4:b |
|---|---|---|---|---|---|
| 0:b | 1 | 2 | 3 | 3 | 4 |
| 1:b | — | 1 | 2 | 2 | 3 |
| 2:b | — | — | 1 | 1 | 3 |
| 3:a | — | — | — | 1 | 1 |
| 4:b | — | — | — | — | 1 |
两端 s[0]、s[4] 相等,dp[0][4] = dp[1][3] + 2 = 4,对应子序列 "bbbb"。它跳过了字符 a,所以不是连续子串。
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = static_cast<int>(s.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
dp[i][i] = 1;
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = static_cast<int>(s.size());
if (n == 0) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
dp[i][i] = 1;
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};两端不等时不是归零,而是尝试缩小候选范围
本题允许跳过字符,因此两端不等时仍可能在区间内部找到很长的回文子序列。它与“判断整个区间是否为回文子串”的布尔状态不同,不能照搬上一题的失败归零逻辑。
- 时间复杂度:
- 空间复杂度:
两道回文题的区别:
| 对比项 | 回文子串 | 最长回文子序列 |
|---|---|---|
| 是否要求连续 | 必须连续 | 允许跳过字符,保持相对顺序 |
| 任务 | 统计所有回文区间的数量 | 求最长回文子序列的长度 |
| 状态类型 | 布尔值:整个区间是否回文 | 整数:区间内可选出的最优长度 |
| 两端不等 | 当前区间不是回文 | 舍去左端或右端,取较大值 |
| 最终答案 | 累加所有为 true 的区间 | dp[0][n - 1](非空串) |
四十四、动态规划总结
一、动态规划五部曲
- 确定状态与下标含义:先用一句完整的话说明
dp表示什么。明确是“必须以当前位置结尾”“前缀中的最优值”,还是“闭区间内的最优值”;再区分求最大值、最小值、方案数或可行性。 - 确定递推公式:枚举最后一步或当前决策,说明每个候选状态来自哪里。最优值通常取
max/min,互不重叠的计数分支相加,可行性分支取逻辑或,不能混用。 - 确定初始化:由状态定义解释第一行、第一列、对角线与不可达状态。空串、空容量有时代表
0个元素,有时代表1种空选择,不能统一全设为0。 - 确定遍历顺序:先画出状态依赖,再安排循环;只有前置状态已经求出,递推才有效。压缩空间之后,还要重新判断读到的是上一轮还是本轮的值。
- 举例推导
dp数组:用小样例列出状态变化,核对初始化、转移和答案位置;优先检查空输入、单元素、全负数、重复字符及边界容量。
二、三类常见下标含义
| 状态范围 | 典型含义 | 答案通常从哪里取 |
|---|---|---|
| 以当前位置结尾 | LIS、连续递增序列、最大子数组和 | 所有结尾状态的最大值 |
| 两个前缀 | LCS、子序列匹配计数、编辑距离 | 两个完整前缀对应的状态 |
闭区间 [i, j] | 回文区间判断、最长回文子序列 | 根据任务累加区间,或取完整区间 |
三、典型模型与复习入口
| 模型 | 核心关注点 | 相关笔记 |
|---|---|---|
| 基础递推与路径 | 当前状态依赖哪些前置位置,边界是否可达 | 理论基础、网格路径 |
| 背包 | 物品能否重复选、容量含义、计数还是最优值 | 0-1 背包、完全背包、多重背包 |
| 打家劫舍 | 当前选或不选,与相邻位置或子树的关系 | 线性、环形、树形 |
| 股票状态 | 持有与不持有,交易次数、冷冻期和手续费 | 股票入门、冷冻期(待补)、手续费 |
| 子序列与连续片段 | 是否必须连续,状态是否必须以当前位置结尾 | LIS、LCIS、最大子数组和 |
| 字符串匹配与编辑 | 求长度、可行性、方案数还是操作次数 | LCS、判定、计数、编辑距离 |
| 回文区间 | 内部区间依赖,连续子串与非连续子序列的区别 | 回文子串、最长回文子序列 |
四、遍历与边界速查
- 一维 0-1 背包:外层枚举物品,容量倒序,避免同一件物品被重复使用。
- 一维完全背包:外层枚举物品时,容量正序,允许重复使用当前物品;求方案数还要区分物品在外层的组合计数与容量在外层的排列计数。
- 两个前缀的 DP:常从小前缀推到大前缀,表的大小通常为
(m + 1) × (n + 1),额外一行、一列表示空前缀。 - 本节回文区间 DP:左端点从大到小、右端点向右递增;也可以按区间长度从短到长计算,关键是先求出内部或更短区间。
- 树形 DP:先处理子节点,再根据子树状态计算父节点,通常使用后序遍历。
- 数值与答案位置:全负数组不能用
0冒充非空最大和;最少次数问题要区分不可达状态;计数题不能仅凭最终答案较小就忽略中间计数溢出。最终返回哪个状态,必须由定义决定。
2026-11-01(周日)
单调栈(一)
一、单调栈理论基础
什么时候想到单调栈?
对于一维数组,如果要为各个位置寻找左侧或右侧第一个比自己更大或更小的元素,可以考虑单调栈。它通过维护有序的候选集合,避免为每个位置重复向外扫描,是每日温度、柱状图、接雨水等问题中的常见工具。
栈里存什么?
- 通常存储元素的下标,需要比较数值时再通过数组取值。
- 下标既能确定元素位置,也能计算距离或宽度;只存数值会丢失位置信息,尤其无法区分重复值所在的位置。
- 在本节“从左到右寻找右侧第一个更大元素”的写法中,栈里保存的是尚未找到答案的下标。新元素到来时,尝试为栈顶位置确定答案。
单调方向必须说明观察顺序:本节统一按栈底 → 栈顶描述元素值的变化,下标本身则按入栈顺序递增。
| 从左到右扫描时的目标 | 栈底 → 栈顶的元素值 | 弹栈条件 | 弹栈时确定什么 |
|---|---|---|---|
| 右侧第一个严格更大的元素 | 非递增,允许相等 | 当前值 > 栈顶对应值 | 当前下标是被弹出位置的答案 |
| 右侧第一个严格更小的元素 | 非递减,允许相等 | 当前值 < 栈顶对应值 | 当前下标是被弹出位置的答案 |
不要只记“递增栈”或“递减栈”的名称
不同资料可能按相反方向描述栈的单调性。应明确观察顺序,以及比较的是下标还是对应数值。上表只对应从左到右扫描、弹栈确定右侧严格答案的写法;寻找左侧答案或允许相等时,需要根据题意重新确定弹栈条件。
为什么整体是线性时间?
每个下标最多入栈一次、出栈一次。虽然内层有 while,某一天也可能连续弹出多个位置,但整个过程的入栈、出栈总次数不超过线性数量,因此时间复杂度为 ,最坏额外空间为 。这就是用空间换时间,而不是每个位置各扫描一遍后续元素。
二、每日温度
题目:739. 每日温度
给定每天的温度,求每一天还要等待多少天,才能遇到严格更高的温度。若之后没有更暖的一天,答案为 0。这里求的是下标差,不是温度差,也不是未来的最高温度。
解题思路:
- 确定目标:对第
p天,寻找最小的i > p,使temperatures[i] > temperatures[p],答案为i - p。 - 维护栈的含义:栈存放尚未找到更暖日子的下标,对应温度从栈底到栈顶非递增;结果数组全部初始化为
0。 - 处理当前温度:
- 当前温度小于栈顶温度:暂时无法确定栈顶答案,将当前下标入栈。
- 当前温度等于栈顶温度:相等不算升温,保留旧下标,将当前下标入栈。
- 当前温度大于栈顶温度:弹出栈顶下标
p,记录result[p] = i - p,继续检查新的栈顶,直到栈为空或当前温度不再更高。
- 统一入栈:无论属于哪种情况,处理结束后都将当前下标入栈一次,因此前两类无需分别写分支。
- 处理剩余位置:遍历结束后仍留在栈中的日子没有更暖的未来日期,保留默认答案
0。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = static_cast<int>(temperatures.size());
vector<int> result(n, 0);
stack<int> st; // 存下标,对应温度从栈底到栈顶非递增
for (int i = 0; i < n; ++i) {
while (!st.empty()
&& temperatures[i] > temperatures[st.top()]) {
int previous = st.top();
st.pop();
result[previous] = i - previous;
}
st.push(i);
}
return result;
}
};class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = static_cast<int>(temperatures.size());
vector<int> result(n, 0);
stack<int> st; // 存下标,对应温度从栈底到栈顶非递增
for (int i = 0; i < n; ++i) {
while (!st.empty()
&& temperatures[i] > temperatures[st.top()]) {
int previous = st.top();
st.pop();
result[previous] = i - previous;
}
st.push(i);
}
return result;
}
};示例推演:temperatures = [73, 74, 75, 71, 69, 72, 76, 73]。表中的栈用下标表示,顺序为栈底 → 栈顶。
当前下标 i | 当前温度 | 本轮确定的等待天数 | 处理后的栈 |
|---|---|---|---|
| 0 | 73 | 无 | [0] |
| 1 | 74 | result[0] = 1 | [1] |
| 2 | 75 | result[1] = 1 | [2] |
| 3 | 71 | 无 | [2, 3] |
| 4 | 69 | 无 | [2, 3, 4] |
| 5 | 72 | result[4] = 1,result[3] = 2 | [2, 5] |
| 6 | 76 | result[5] = 1,result[2] = 4 | [6] |
| 7 | 73 | 无 | [6, 7] |
最终答案为 [1, 1, 4, 2, 1, 1, 0, 0]。
为什么弹栈时找到的一定是“第一个”更暖的日子?
日期按从左到右的顺序处理。若位置
p在当前日期之前就遇到过更暖的日子,它当时就应被弹出;既然现在仍在栈中,说明之前没有满足条件的日期。当前日一旦比它更暖,就能确定最早答案,不需要继续等待后续日期。
相等不能弹栈,弹栈必须用
while对
[70, 70, 71],前两个70的答案分别为2和1,所以相等温度也要保留各自的下标。当前温度可能同时解决多个待定位置,必须用while连续弹栈,不能只用if处理一次。访问栈顶前应先检查栈非空。
- 时间复杂度:,每个下标最多入栈、出栈各一次
- 空间复杂度:,最坏情况下所有下标都留在栈中;若不计返回数组,辅助栈仍为
2026-11-02(周一)
单调栈(二)
三、下一个更大元素 I
给定两个各自没有重复元素的数组 nums1、nums2,且 nums1 是 nums2 的子集。对 nums1 中的每个值,找到它在 nums2 中的位置,再返回其右侧第一个严格更大的元素值;不存在则返回 -1,结果顺序与 nums1 一致。
与每日温度相比,核心仍是找右侧第一个严格更大元素,但这里不返回等待距离,而且只需回答 nums1 中的查询。
解题思路:
- 建立查询映射:用
unordered_map<int, int>记录“nums1中的元素值 → 它在nums1中的下标”。无重复值保证这个映射唯一。 - 初始化结果:长度为
nums1.size(),全部设为-1,表示尚未找到更大元素。 - 扫描
nums2:栈存放nums2中尚未找到右侧更大元素的下标,对应数值从栈底到栈顶非递增。 - 弹栈并填写查询答案:当前值
nums2[i]大于栈顶对应值时,弹出下标previous。若nums2[previous]出现在查询映射中,就将nums2[i]填入它在结果数组中的位置;否则只弹栈,不记录查询答案。 - 当前下标入栈:处理完所有能被当前值解决的位置后,将
i入栈。最终未被解决的查询保留-1。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<int> result(m, -1);
unordered_map<int, int> queryIndex;
for (int i = 0; i < m; ++i) {
queryIndex[nums1[i]] = i;
}
stack<int> st; // 存 nums2 的下标
for (int i = 0; i < n; ++i) {
while (!st.empty() && nums2[i] > nums2[st.top()]) {
int previous = st.top();
st.pop();
auto it = queryIndex.find(nums2[previous]);
if (it != queryIndex.end()) {
result[it->second] = nums2[i];
}
}
st.push(i);
}
return result;
}
};class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int m = static_cast<int>(nums1.size());
int n = static_cast<int>(nums2.size());
vector<int> result(m, -1);
unordered_map<int, int> queryIndex;
for (int i = 0; i < m; ++i) {
queryIndex[nums1[i]] = i;
}
stack<int> st; // 存 nums2 的下标
for (int i = 0; i < n; ++i) {
while (!st.empty() && nums2[i] > nums2[st.top()]) {
int previous = st.top();
st.pop();
auto it = queryIndex.find(nums2[previous]);
if (it != queryIndex.end()) {
result[it->second] = nums2[i];
}
}
st.push(i);
}
return result;
}
};示例:nums1 = [4, 1, 2]、nums2 = [1, 3, 4, 2]。
| 查询值 | 在 nums1 中的下标 | 在 nums2 中的下标 | 右侧第一个严格更大值 |
|---|---|---|---|
| 4 | 0 | 2 | 不存在,填 -1 |
| 1 | 1 | 0 | 3 |
| 2 | 2 | 3 | 不存在,填 -1 |
结果为 [-1, 3, -1]。扫描到 3 时,弹出 nums2 中值为 1 的位置,通过映射找到查询下标 1,填写 result[1] = 3。
区分三个对象:扫描下标、查询下标、答案值
栈中存的是
nums2的下标;哈希表的键是元素值,值是它在nums1中的下标;最终写入结果的是右侧更大的元素值,而不是它的下标,也不是下标差。不要把映射误写成“nums2下标 →nums1下标”。
“第一个更大”不是“右侧最大”
例如在
[1, 3, 4, 2]中,1的答案是先遇到的3,不是更大的4。代码用find检查查询是否存在,避免用operator[]查询不存在的键时意外插入默认下标。
- 时间复杂度:平均 ,哈希操作按平均 计算,每个扫描下标最多入栈、出栈各一次
- 空间复杂度:,包括查询映射、辅助栈与结果数组;其中
m、n分别为两个数组的长度
四、下一个更大元素 II
给定一个循环数组,最后一个元素之后可以继续访问第一个元素。对每个位置,按向右循环的顺序寻找第一个严格更大的元素值;不存在则返回 -1。本题允许重复值,也允许负数。
解题思路:
- 把循环搜索变成线性扫描:可以在概念上将数组拼接两遍,让原数组末尾的位置也有机会查看开头的元素。但不必真的复制数组。
- 用取模模拟两轮:虚拟下标
i从0遍历到2 * n - 1,真实下标为current = i % n。 - 维护待定下标:栈中存原数组的下标,对应数值从栈底到栈顶非递增。当前值严格大于栈顶对应值时,连续弹栈并记录答案值。
- 只在第一轮入栈:当
i < n时将current入栈;第二轮仅用于补全跨越数组末尾的答案,不重复加入同一查询位置。 - 保留未解决项:始终找不到严格更大值的位置保留
-1,例如所有全局最大值的位置。
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = static_cast<int>(nums.size());
vector<int> result(n, -1);
if (n == 0) {
return result;
}
stack<int> st; // 存原数组下标,只在第一轮入栈
for (int i = 0; i < 2 * n; ++i) {
int current = i % n;
while (!st.empty() && nums[current] > nums[st.top()]) {
int previous = st.top();
st.pop();
result[previous] = nums[current];
}
if (i < n) {
st.push(current);
}
}
return result;
}
};class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = static_cast<int>(nums.size());
vector<int> result(n, -1);
if (n == 0) {
return result;
}
stack<int> st; // 存原数组下标,只在第一轮入栈
for (int i = 0; i < 2 * n; ++i) {
int current = i % n;
while (!st.empty() && nums[current] > nums[st.top()]) {
int previous = st.top();
st.pop();
result[previous] = nums[current];
}
if (i < n) {
st.push(current);
}
}
return result;
}
};示例推演:nums = [1, 2, 1]。栈中用原数组下标表示,顺序为栈底 → 栈顶。
虚拟下标 i | 真实下标 i % n | 当前值 | 本轮确定的答案 | 处理后的栈 |
|---|---|---|---|---|
| 0 | 0 | 1 | 无 | [0] |
| 1 | 1 | 2 | result[0] = 2 | [1] |
| 2 | 2 | 1 | 无 | [1, 2] |
| 3 | 0 | 1 | 无;第二轮不入栈 | [1, 2] |
| 4 | 1 | 2 | result[2] = 2 | [1] |
| 5 | 2 | 1 | 无;第二轮不入栈 | [1] |
最终答案为 [2, -1, 2]。末尾的 1 通过第二轮扫描找到开头之后的 2;值为 2 的位置没有更大元素,保留 -1。
严格比较,不把自己或相同值当成答案
弹栈条件使用
>,不是>=。循环回到自身时数值相等,不会错误地匹配自己;多个最大值也不会互相充当“更大元素”。第二轮不入栈,使每个原下标最多入栈、出栈各一次。
找的是“下一个更大值”,不是“下一个最大值”
拼接数组再计算并截取前
n个答案也是可行思路,但会额外复制数据。上述取模写法保持原数组不变。空数组在取模前直接返回;-1只是题目规定的输出值,不用于判断位置是否已经处理,因此数组中本身有-1也不影响算法。
- 时间复杂度:,两轮扫描仍为线性,每个下标最多入栈、出栈各一次
- 空间复杂度:,包括结果数组和辅助栈,无需复制原数组
三道“右侧第一个更大”题的区别:
| 对比项 | 每日温度 | 下一个更大元素 I | 下一个更大元素 II |
|---|---|---|---|
| 扫描对象 | 温度数组 | nums2 | 循环数组 nums |
| 结果顺序 | 原数组顺序 | 查询数组 nums1 的顺序 | 原数组顺序 |
| 返回内容 | 等待天数,即下标差 | 更大元素的值 | 更大元素的值 |
| 找不到时 | 0 | -1 | -1 |
| 额外关键点 | 保留相同温度的不同位置 | 无重复值、子集关系、哈希映射 | 取模扫描两轮,第一轮入栈 |
2026-11-03(周二)
单调栈(三)
五、接雨水
题目:42. 接雨水
给定非负柱高数组,每根柱子的宽度为 1,求雨后能接住的总水量。可以按竖直列计算每个位置的水量,也可以用单调栈按水平层累加凹槽面积。
方法一:暴力按列计算
第 i 列能达到的水位由左右两侧最高柱子中较矮的一侧决定。下面把当前位置也纳入左右最大值,定义:
leftMax:区间[0, i]的最大柱高。rightMax:区间[i, n - 1]的最大柱高。- 当前列水量为
min(leftMax, rightMax) - height[i],宽度为1;由于最大值均包含当前柱高,这个差值不会为负。
首尾两列无法蓄水,直接跳过。对每个内部位置分别扫描两侧即可。
class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
int sum = 0;
for (int i = 1; i < n - 1; ++i) {
int leftMax = height[i];
int rightMax = height[i];
for (int left = 0; left < i; ++left) {
leftMax = max(leftMax, height[left]);
}
for (int right = i + 1; right < n; ++right) {
rightMax = max(rightMax, height[right]);
}
sum += min(leftMax, rightMax) - height[i];
}
return sum;
}
};class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
int sum = 0;
for (int i = 1; i < n - 1; ++i) {
int leftMax = height[i];
int rightMax = height[i];
for (int left = 0; left < i; ++left) {
leftMax = max(leftMax, height[left]);
}
for (int right = i + 1; right < n; ++right) {
rightMax = max(rightMax, height[right]);
}
sum += min(leftMax, rightMax) - height[i];
}
return sum;
}
};- 时间复杂度:,每列都重复扫描左右两侧
- 空间复杂度:
方法二:前后缀最大值预处理
暴力解法的重复计算在于反复寻找左右最高柱。用两个数组预处理:
maxLeft[i] = max(maxLeft[i - 1], height[i]),从左向右计算。maxRight[i] = max(maxRight[i + 1], height[i]),从右向左计算。- 最后按列累加
min(maxLeft[i], maxRight[i]) - height[i]。
class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
if (n < 3) {
return 0;
}
vector<int> maxLeft(n, 0);
vector<int> maxRight(n, 0);
maxLeft[0] = height[0];
for (int i = 1; i < n; ++i) {
maxLeft[i] = max(maxLeft[i - 1], height[i]);
}
maxRight[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
maxRight[i] = max(maxRight[i + 1], height[i]);
}
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += min(maxLeft[i], maxRight[i]) - height[i];
}
return sum;
}
};class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
if (n < 3) {
return 0;
}
vector<int> maxLeft(n, 0);
vector<int> maxRight(n, 0);
maxLeft[0] = height[0];
for (int i = 1; i < n; ++i) {
maxLeft[i] = max(maxLeft[i - 1], height[i]);
}
maxRight[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
maxRight[i] = max(maxRight[i + 1], height[i]);
}
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += min(maxLeft[i], maxRight[i]) - height[i];
}
return sum;
}
};示例:height = [3, 0, 2, 0, 4]。
下标 i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 柱高 | 3 | 0 | 2 | 0 | 4 |
maxLeft[i] | 3 | 3 | 3 | 3 | 4 |
maxRight[i] | 4 | 4 | 4 | 4 | 4 |
| 当前列水量 | 0 | 3 | 1 | 3 | 0 |
总水量为 7。
前后缀数组与常数空间双指针不是同一种实现
这里预存了每个位置的左右最大值,额外空间为 。也可以用左右双指针配合两侧已知最大值做到 辅助空间,但不能把上面这段使用两个数组的代码写成常数空间解法。
- 时间复杂度:
- 空间复杂度:
方法三:单调栈按水平层累加
栈存柱子的下标,对应高度从栈底 → 栈顶非递增。当前柱子高于栈顶时,说明可能遇到了凹槽的右侧边界:
- 弹出的下标
mid作为当前待填水层的底部。 - 弹栈后若栈为空,说明没有左边界,不能蓄水,停止本轮弹栈。
- 否则新的栈顶
left是左边界,当前下标i是右边界。 - 本次新增水层的高度为
min(height[left], height[i]) - height[mid],宽度为i - left - 1,两者相乘后累加。 - 持续弹栈,可能继续计算更高的一层;最后将当前下标入栈。
class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
stack<int> st;
int sum = 0;
for (int i = 0; i < n; ++i) {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (st.empty()) {
break;
}
int left = st.top();
int waterHeight = min(height[left], height[i]) - height[mid];
int width = i - left - 1;
sum += waterHeight * width;
}
st.push(i);
}
return sum;
}
};class Solution {
public:
int trap(vector<int>& height) {
int n = static_cast<int>(height.size());
stack<int> st;
int sum = 0;
for (int i = 0; i < n; ++i) {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (st.empty()) {
break;
}
int left = st.top();
int waterHeight = min(height[left], height[i]) - height[mid];
int width = i - left - 1;
sum += waterHeight * width;
}
st.push(i);
}
return sum;
}
};同一示例的分层过程:height = [3, 0, 2, 0, 4],只列出新增水量大于 0 的弹栈步骤。
当前右边界 i | 弹出的底部 mid | 左边界 left | 新增水层高度 | 宽度 | 新增水量 |
|---|---|---|---|---|---|
| 2 | 1 | 0 | min(3, 2) - 0 = 2 | 1 | 2 |
| 4 | 3 | 2 | min(2, 4) - 0 = 2 | 1 | 2 |
| 4 | 2 | 0 | min(3, 4) - 2 = 1 | 3 | 3 |
总水量为 2 + 2 + 3 = 7。各次累加的是不同高度层中的新增部分,不是将同一片水重复计算。
相等柱高可以保留,不是必须替换成最右位置
本实现对相等高度直接入栈。后续若弹出同高柱子,某次新增水层高度可能为
0,随后继续弹栈仍能得到正确边界。也可以设计合并同高柱子的写法,但本实现统一使用while加最后一次入栈,避免多分支中对栈进行冗余操作。
- 时间复杂度:,每个下标最多入栈、出栈各一次
- 空间复杂度:
六、柱状图中最大的矩形
每根柱子宽度为 1,求柱状图中能完全容纳的最大矩形面积。矩形覆盖连续若干柱子,其高度不能超过这段区间中的最矮柱高。
解题思路:
- 维护待扩展柱子:栈中存下标,对应高度从栈底 → 栈顶非递减。更高或等高的柱子到来时,暂时无法确定旧柱子能向右延伸多远,直接入栈。
- 遇到更矮柱子时结算:当前高度严格小于栈顶高度,弹出下标
mid,以bars[mid]为候选矩形高度。当前下标i是右侧第一个阻挡该高度的位置。 - 计算宽度:弹栈后的栈顶为
left,候选矩形覆盖开区间(left, i),宽度为i - left - 1,面积为bars[mid] * (i - left - 1),更新全局最大值。 - 加入零高度哨兵:数组前方的
0提供左侧边界,后方的0触发剩余正高度柱子的结算。柱高均非负,前方的零高度边界不会被更小值弹出,因此弹出正高度柱子后可以安全读取新的栈顶。 - 避免改动输入:在局部数组
bars中添加哨兵,不对传入的heights直接插入元素,方便重复调用与复用原数据。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = static_cast<int>(heights.size());
vector<int> bars(n + 2, 0);
for (int i = 0; i < n; ++i) {
bars[i + 1] = heights[i];
}
stack<int> st;
st.push(0);
int result = 0;
for (int i = 1; i < n + 2; ++i) {
while (!st.empty() && bars[i] < bars[st.top()]) {
int mid = st.top();
st.pop();
int left = st.top();
int width = i - left - 1;
result = max(result, bars[mid] * width);
}
st.push(i);
}
return result;
}
};class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = static_cast<int>(heights.size());
vector<int> bars(n + 2, 0);
for (int i = 0; i < n; ++i) {
bars[i + 1] = heights[i];
}
stack<int> st;
st.push(0);
int result = 0;
for (int i = 1; i < n + 2; ++i) {
while (!st.empty() && bars[i] < bars[st.top()]) {
int mid = st.top();
st.pop();
int left = st.top();
int width = i - left - 1;
result = max(result, bars[mid] * width);
}
st.push(i);
}
return result;
}
};示例推导:heights = [2, 1, 5, 6, 2, 3],添加哨兵后为 [0, 2, 1, 5, 6, 2, 3, 0]。
- 扫描到局部数组下标
5、高度为2时,先弹出高度6的柱子,宽度为1,面积为6。 - 接着弹出高度
5的柱子,此时左边界下标为2,右边界下标为5,宽度为5 - 2 - 1 = 2,面积为5 * 2 = 10。 - 后续处理及末尾哨兵结算不会得到更大面积,最终答案为
10。
保留相等高度时,左边界不一定严格更矮
本实现保留同高下标,所以弹栈后左侧边界的高度可能与
bars[mid]相等,此次候选宽度未必是这个高度的最大宽度。继续弹出更早的同高下标时,会得到更宽的矩形,因此整体最大值仍正确。例如[2, 2]会先算出面积2,再算出面积4。不能在这种写法中声称每次都找到了“左右两个严格更小边界”。
宽度为什么要减 1?
left和i是当前候选的边界位置,实际覆盖的是left + 1到i - 1,所以宽度为i - left - 1。末尾哨兵负责结算递增序列中尚未弹出的柱子,不能漏掉;零高度本身不会贡献正面积。
- 时间复杂度:,每个局部数组下标最多入栈、出栈各一次
- 空间复杂度:,包括局部哨兵数组和辅助栈
两类面积问题的区别:
| 对比项 | 接雨水(单调栈) | 柱状图中最大的矩形 |
|---|---|---|
| 栈底 → 栈顶的高度 | 非递增 | 非递减 |
| 触发弹栈 | 当前柱子更高,形成右侧挡板 | 当前柱子更矮,阻止继续扩展 |
| 被弹出柱子的角色 | 凹槽底部 | 候选矩形高度 |
| 本次面积的高度 | 两边界较矮高度减去底部高度 | 被弹出柱子的高度 |
| 本次面积的宽度 | right - left - 1 | right - left - 1 |
| 汇总方式 | 累加不同水层的面积 | 取候选矩形面积的最大值 |
2026-11-04(周三)
图论(一)
一、图论理论基础
学习重点:先识别图的方向、边权与连通性,再选择存储结构和算法。先把邻接矩阵、邻接表的建图写熟,再分别掌握 DFS、BFS;进入最短路前,先判断是否有负边权、问题是单源查询还是多源查询。
图论题常以 ACM 模式练习,需要自己处理输入、建图和输出。除了算法本身,还要特别留意节点编号、输入终止条件、多组数据的状态清理,以及题目要求的输出格式。
图的分类与度:
图可以记为 G = (V, E),其中 V 为顶点集合、E 为边集合。讨论复杂度时,下面用 n 表示顶点数、m 表示边数。
| 分类维度 | 类型 | 含义 |
|---|---|---|
| 是否有方向 | 有向图 / 无向图 | 有向边 u → v 只表示从 u 到 v;无向边连接两个端点,允许双向通行 |
| 是否有边权 | 带权图 / 无权图 | 边可以附带距离、费用等权值;无权图的每条边通常视为一次等价的移动 |
方向和边权是两个独立维度:有向图、无向图都可以带权或不带权,不能把“无向图”与“带权图”当成同一种分类。
- 无向图的度:与某顶点关联的边的端点数量;在没有自环的图中,就是连接该顶点的边数。若允许自环,一条自环对该顶点的度贡献为
2。 - 有向图的出度:从该顶点出发的边数。
- 有向图的入度:指向该顶点的边数;一条有向自环对入度、出度各贡献
1。
连通性与连通分量
| 概念 | 定义与注意点 |
|---|---|
| 无向图中的连通 | 两个顶点之间存在一条路径;不要求它们之间直接有边 |
| 连通图 | 无向图中任意两个顶点之间都存在路径 |
| 强连通图 | 有向图中任意两个顶点 u、v,既存在从 u 到 v 的有向路径,也存在从 v 到 u 的有向路径 |
| 连通分量 | 无向图中的极大连通子图;整张图可以分成一个或多个连通分量 |
| 强连通分量 | 有向图中的极大强连通子图;不是只看边的方向被忽略后是否连通 |
“任意两点可达”是连通图的条件,不是所有图的默认性质
图可能不连通。这里的“极大”表示不能再加入图中其他顶点而仍保持对应的连通性质,不是指全图中规模最大的那一块;一个图可以有多个大小不同的连通分量。
图的存储与建图
一、邻接矩阵
使用二维数组记录顶点之间是否有边或边的权值。对于无权图,可以用 graph[u][v] = 1 表示存在从 u 到 v 的边,0 表示不存在。
- 优点:结构直观,判断指定两点之间是否存在边只需 时间;适合顶点数较小、边较密集或需要频繁查边的场景。
- 缺点:无论实际有多少边,都需要 空间;枚举一个顶点的邻居通常要扫描一整行,完整扫描矩阵需要 时间。稀疏图中会浪费大量空间。
- 对无向图,一条边需要同时标记
graph[u][v]和graph[v][u]。
有向无权图的 ACM 建图示例:假设第一行输入 n m,后续 m 行输入边 u v,顶点编号为 1..n。下面代码仅演示读取和建图,后续遍历、答案计算与输出应按具体题目补充。
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
graph[u][v] = 1;
// 无向图还需:graph[v][u] = 1;
}
// 后续按题意遍历、计算并输出答案。
return 0;
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
graph[u][v] = 1;
// 无向图还需:graph[v][u] = 1;
}
// 后续按题意遍历、计算并输出答案。
return 0;
}无权矩阵的 0/1 约定不能直接照搬到任意带权图
边权可能为
0,因此带权矩阵必须区分“没有边”与“存在一条零权边”,常用专门的无边标记。若允许重边,还要按任务决定保留最小权值、累计数量还是保存全部边;上面的 0/1 矩阵只记录是否存在边。
二、邻接表
为每个顶点维护一份相邻顶点或出边的列表。在 C++ 中,常用 vector<vector<int>> 表示,不必真的使用链表;带权图可以在每条邻接记录中同时保存终点与权值。
- 优点:空间为 ,适合稀疏图;枚举指定顶点的所有出边时,只需访问实际存储的邻接记录。
- 缺点:若邻接列表未排序、也没有额外哈希索引,判断指定边
u → v是否存在,通常需要扫描u的邻接列表,时间为 ;无向图对应 。 - 对无向图,一条普通边在两端的邻接列表中各存一次,因此通常保存
2m条邻接记录,渐进空间复杂度仍为 。
相同输入约定下的有向无权图建图示例:
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
// 无向图还需:graph[v].push_back(u);
}
// 后续按题意遍历、计算并输出答案。
return 0;
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
// 无向图还需:graph[v].push_back(u);
}
// 后续按题意遍历、计算并输出答案。
return 0;
}同一张图的两种表示:顶点为 {1, 2, 3},有向边为 1 → 2、1 → 3、3 → 2。
| 顶点 | 邻接矩阵对应行(列顺序 1、2、3) | 邻接表 |
|---|---|---|
| 1 | [0, 1, 1] | [2, 3] |
| 2 | [0, 0, 0] | [] |
| 3 | [0, 1, 0] | [2] |
例如顶点 1 的出度为 2、入度为 0,顶点 2 的出度为 0、入度为 2。这张图不是强连通图,因为顶点 2 无法沿有向边回到顶点 1。
存储方式速查:
| 操作或特点 | 邻接矩阵 | 邻接表 |
|---|---|---|
| 空间复杂度 | ||
| 建图时间(含初始化) | ||
| 检查指定边是否存在 | 扫描起点的邻接列表,取决于其度数 | |
| 枚举一个顶点的邻居 | 与实际邻接记录数量成正比 | |
| 常见适用场景 | 顶点数小、稠密图、频繁查边 | 稀疏图、按边遍历、一般搜索 |
度数符号与顶点总数不能混用
n是全图顶点数,deg(u)是顶点u的度;有向图的deg⁺(u)表示出度。邻接表的查边代价取决于起点列表长度,不能把“某节点连接的边数”同时写成表示全图顶点数的符号。用类封装顶点或边是一种代码组织方式,不是与邻接矩阵、邻接表并列的存储原理。
图的遍历与学习路线
| 方式 | 核心过程 | 常用辅助结构 | 需要注意 |
|---|---|---|---|
| 深度优先搜索(DFS) | 沿一条路径深入,无法继续后再回退 | 递归调用栈或显式栈 | 普通可达性遍历需标记已访问顶点;深链图中要考虑递归深度 |
| 广度优先搜索(BFS) | 按距离起点的层数逐层扩展 | 队列 | 普通遍历通常在入队时标记,避免重复入队;无权图中可求最少边数的路径 |
- 单次从一个起点出发,只能访问从它出发可达的部分;无向图若要遍历全图或统计连通分量,需要枚举所有顶点,对未访问的顶点重新启动搜索。
- 使用邻接表完整遍历全图,DFS、BFS 的时间复杂度均为 ;使用邻接矩阵枚举邻居时,通常为 。访问标记、队列或栈的最坏辅助空间为 。
- 有向图中从某点能到达其他点,并不代表其他点也能返回;普通搜索可以判断可达性,但不能仅靠一次搜索就认定强连通性。
接下来的学习顺序:
- 先熟悉有向 / 无向、带权 / 无权、编号从
0还是从1开始,以及一条无向边需要存两次的规则。 - 分别写熟邻接矩阵、邻接表的建图,再练习 DFS、BFS 的访问标记和遍历过程。
- 做题前先判断是可达性、连通分量、路径枚举,还是最短路问题,不要把“能找到一条路径”当成“找到了最短路径”。
- 进入最短路时,再根据边权是否为负、是否等权、单源还是多源,以及图的规模选择算法;BFS 的最少边数结论不能直接用于任意带权图。
2026-11-05(周四)
图论(二)
二、所有可达路径
题目:卡码网 98. 可达路径
给定节点编号为 1..n 的有向无环图(DAG),输出所有从节点 1 到节点 n 的路径。题目保证没有自环、没有平行边;不同路径可以经过相同的中间节点。
输入输出要求:
- 第一行输入
n m,随后m行输入s t,表示有向边s → t,不能反向再加一条边。 - 每条路径单独一行,节点之间用一个空格隔开,行末不能有多余空格;路径之间的输出顺序不限。
- 没有可达路径时,输出
-1。
DFS 与回溯思路:
path保存从起点到当前节点的路径,调用搜索前先放入起点1,不是节点0。- 到达终点
n时,将当前路径复制到result,并立即返回。 - 否则枚举当前节点的所有出边,将下一节点加入
path,递归搜索。 - 从递归返回后执行
path.pop_back(),撤销本次选择,使下一条分支从同一个路径前缀出发。
枚举所有路径不能使用“访问一次后永不撤销”的全局
visited例如有边
1 → 2、1 → 3、2 → 4、3 → 4、4 → 5,两条答案都经过节点4,不能在第一条路径访问后就阻止第二条路径进入它。本题保证无环,不会沿当前路径绕回自身,因此无需防环标记。若换成含环图并只枚举简单路径,应使用进入时标记、回溯时撤销的当前路径标记;不能直接照搬下面的无标记代码。
方法一:邻接矩阵
graph[u][v] = 1 表示存在有向边 u → v。每次搜索扫描当前节点对应的整行,查找所有出边。
#include <iostream>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>>& graph, int current, int target,
vector<int>& path, vector<vector<int>>& result) {
if (current == target) {
result.push_back(path);
return;
}
for (int next = 1; next < static_cast<int>(graph.size()); ++next) {
if (graph[current][next] == 0) {
continue;
}
path.push_back(next);
dfs(graph, next, target, path, result);
path.pop_back();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
int from, to;
cin >> from >> to;
graph[from][to] = 1;
}
vector<int> path{1};
vector<vector<int>> result;
dfs(graph, 1, n, path, result);
if (result.empty()) {
cout << -1 << '\n';
}
for (const auto& onePath : result) {
for (int i = 0; i < static_cast<int>(onePath.size()); ++i) {
if (i > 0) {
cout << ' ';
}
cout << onePath[i];
}
cout << '\n';
}
return 0;
}#include <iostream>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>>& graph, int current, int target,
vector<int>& path, vector<vector<int>>& result) {
if (current == target) {
result.push_back(path);
return;
}
for (int next = 1; next < static_cast<int>(graph.size()); ++next) {
if (graph[current][next] == 0) {
continue;
}
path.push_back(next);
dfs(graph, next, target, path, result);
path.pop_back();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
int from, to;
cin >> from >> to;
graph[from][to] = 1;
}
vector<int> path{1};
vector<vector<int>> result;
dfs(graph, 1, n, path, result);
if (result.empty()) {
cout << -1 << '\n';
}
for (const auto& onePath : result) {
for (int i = 0; i < static_cast<int>(onePath.size()); ++i) {
if (i > 0) {
cout << ' ';
}
cout << onePath[i];
}
cout << '\n';
}
return 0;
}方法二:邻接表
用 graph[u] 保存从 u 出发能够直接到达的顶点,只遍历实际存在的出边。邻接表可以用 list,也可以用 vector;这里统一使用与前一天建图笔记相同的 vector<vector<int>>。
#include <iostream>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>>& graph, int current, int target,
vector<int>& path, vector<vector<int>>& result) {
if (current == target) {
result.push_back(path);
return;
}
for (int next : graph[current]) {
path.push_back(next);
dfs(graph, next, target, path, result);
path.pop_back();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int from, to;
cin >> from >> to;
graph[from].push_back(to);
}
vector<int> path{1};
vector<vector<int>> result;
dfs(graph, 1, n, path, result);
if (result.empty()) {
cout << -1 << '\n';
}
for (const auto& onePath : result) {
for (int i = 0; i < static_cast<int>(onePath.size()); ++i) {
if (i > 0) {
cout << ' ';
}
cout << onePath[i];
}
cout << '\n';
}
return 0;
}#include <iostream>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>>& graph, int current, int target,
vector<int>& path, vector<vector<int>>& result) {
if (current == target) {
result.push_back(path);
return;
}
for (int next : graph[current]) {
path.push_back(next);
dfs(graph, next, target, path, result);
path.pop_back();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int from, to;
cin >> from >> to;
graph[from].push_back(to);
}
vector<int> path{1};
vector<vector<int>> result;
dfs(graph, 1, n, path, result);
if (result.empty()) {
cout << -1 << '\n';
}
for (const auto& onePath : result) {
for (int i = 0; i < static_cast<int>(onePath.size()); ++i) {
if (i > 0) {
cout << ' ';
}
cout << onePath[i];
}
cout << '\n';
}
return 0;
}示例:
输入:
5 5
1 3
3 5
1 2
2 4
4 55 5
1 3
3 5
1 2
2 4
4 5一种合法输出:
1 3 5
1 2 4 51 3 5
1 2 4 5邻接矩阵通常按节点编号枚举,邻接表通常按边的输入顺序枚举,因此两份程序的输出顺序可能不同,但路径集合应一致。
复杂度说明:设 S 为实际搜索到的路径前缀数量,即递归调用次数(包括最终无法到达终点的分支);L 为所有输出路径的节点数之和。
| 实现 | 时间复杂度(含建图、复制和输出路径) | 空间复杂度(含保存答案) |
|---|---|---|
| 邻接矩阵 | ||
| 邻接表 |
路径枚举不是普通的“每个顶点只访问一次”
DAG 中的路径数量也可能呈指数增长,不能把枚举全部路径的时间写成普通 DFS 的 。两份代码的当前路径和递归栈深度最多为 ,另需保存所有答案的 空间;若不必保留答案,可以在到达终点时直接输出以减少存储。
三、广度优先搜索理论基础
BFS 使用队列按照层次扩展:先处理起点,再处理距起点一条边的节点、两条边的节点,以此类推。在无权图或每步代价相同的网格中,首次发现某个位置时,对应的边数或步数就是最少的;任意带权图不能直接套用这一结论。
核心流程:
- 检查起点是否合法、是否允许通行、是否已经访问。
- 将起点标记为已访问并入队。
- 循环取出队首,枚举它的相邻位置。
- 对合法、可通行且尚未访问的相邻位置,立即标记并入队,直到队列为空。
入队时标记,不等到出队时才标记
多个位置可能同时指向同一个邻居。若等到出队才标记,该邻居可能在此之前被反复加入队列。入队时标记能保证每个位置最多入队一次;普通连通区域遍历中的
visited不需要在返回或出队后撤销。
四方向网格 BFS 模板:
- 约定网格为规则矩形,字符
'1'表示可通行,'0'表示障碍;其他题目应替换对应的通行判断。 - 调用前由外部创建与
grid同形状、初始值为false的visited。函数不重置它,便于多次搜索时复用访问状态。 - 下面模板只标记从起点可达的区域;若要求最短距离或还原路径,需要另外维护距离数组或前驱记录。
#include <queue>
#include <utility>
#include <vector>
using namespace std;
void bfs(const vector<vector<char>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return;
}
int cols = static_cast<int>(grid[0].size());
if (x < 0 || x >= rows || y < 0 || y >= cols
|| grid[x][y] != '1' || visited[x][y]) {
return;
}
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != '1' || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
que.push({nextX, nextY});
}
}
}#include <queue>
#include <utility>
#include <vector>
using namespace std;
void bfs(const vector<vector<char>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return;
}
int cols = static_cast<int>(grid[0].size());
if (x < 0 || x >= rows || y < 0 || y >= cols
|| grid[x][y] != '1' || visited[x][y]) {
return;
}
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != '1' || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
que.push({nextX, nextY});
}
}
}示例:从 (0, 0) 出发,网格为:
1 1 0
0 1 1
1 0 11 1 0
0 1 1
1 0 1依次发现的层次为 (0,0) → (0,1) → (1,1) → (1,2) → (2,2)。左下角的 (2,0) 虽然可通行,但与起点不连通,不会被本次 BFS 标记;障碍也不能入队。
- 时间复杂度:最坏 ,每个可达格子最多入队一次,每次检查四个方向
- 空间复杂度:最坏 ,包括访问标记与队列;其中
R、C为网格行数、列数
普通遍历与路径枚举的区别:
| 对比项 | 普通 BFS / DFS 可达性遍历 | DFS 枚举所有路径 |
|---|---|---|
| 目标 | 找到可达节点、连通区域,或按层求距离 | 找出所有满足条件的完整路径 |
| 同一顶点能否从不同分支再次展开 | 通常不需要,访问后永久标记 | 可能需要,否则会漏掉其他路径 |
| 撤销什么状态 | 普通访问标记不撤销 | 当前路径需要入栈、出栈;必要的防环标记也随路径撤销 |
| 是否必须考虑环 | 用访问标记避免重复扩展 | DAG 可不加防环标记;一般含环图需明确是否枚举简单路径 |
2026-11-06(周五)
图论(三)
四、岛屿数量
给定由整数 1(陆地)和 0(水域)组成的网格,统计岛屿数量。上下左右相邻的陆地属于同一座岛,对角线相邻不算连接;网格外视为水域,接触网格边界的陆地也要计入岛屿。
输入第一行是行数、列数,后续逐行输入网格,最后输出一个整数。题目中的行数、列数均不超过 50。本题使用整数网格,判断陆地应写 grid[x][y] == 1,不要与前一天字符网格模板中的 '1' 混淆。
核心思路:统计陆地连通块
- 创建与网格同形状、初始为
false的visited。 - 从上到下、从左到右扫描每个格子,跳过水域和已经访问的陆地。
- 每遇到一块尚未访问的陆地,说明发现了一座新岛,答案增加
1。 - 从这个位置启动 DFS 或 BFS,将整座岛屿的所有陆地标记为已访问。
- 后续扫描再次遇到同一座岛的其他陆地时直接跳过,既不会漏计,也不会重复计数。
每次发现新连通块加 1,不是每访问一个陆地格子加 1
一座岛可以由许多格子组成。外层扫描负责发现并统计岛屿,内层搜索只负责标记整座岛;如果在搜索每个邻居时都累加答案,算出的就会变成陆地格子数。
方法一:深度优先搜索(DFS)
进入 dfs 后,先标记当前陆地,再递归访问上下左右未访问的陆地。主循环保证传入的是合法、尚未访问的陆地,因此函数内部不必再次检查起点。
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
visited[x][y] = true;
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1 && !visited[nextX][nextY]) {
dfs(grid, visited, nextX, nextY);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
++result;
dfs(grid, visited, i, j);
}
}
}
cout << result << '\n';
return 0;
}#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
visited[x][y] = true;
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1 && !visited[nextX][nextY]) {
dfs(grid, visited, nextX, nextY);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
++result;
dfs(grid, visited, i, j);
}
}
}
cout << result << '\n';
return 0;
}- 时间复杂度:,外层扫描所有格子,陆地在搜索中也只会被访问一次,每次检查四个方向
- 空间复杂度:最坏 ,包括访问标记和递归调用栈;其中
R、C为行数、列数
访问标记不回溯,递归深度不一定只有行数或列数
本题只统计连通块,不枚举路径,访问过的陆地不能在递归返回时重新设为未访问。较长的陆地链可能让递归深度达到 ;当网格规模更大、递归栈受限时,可以改用显式栈或下面的 BFS。
方法二:广度优先搜索(BFS)
主循环与 DFS 相同,只是把连通区域的标记过程改为队列逐层扩展。起点和每个新发现的陆地都在入队时立即标记,而不是等出队时才标记。
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void bfs(const vector<vector<int>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != 1 || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
que.push({nextX, nextY});
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
++result;
bfs(grid, visited, i, j);
}
}
}
cout << result << '\n';
return 0;
}#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void bfs(const vector<vector<int>>& grid,
vector<vector<bool>>& visited, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != 1 || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
que.push({nextX, nextY});
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
++result;
bfs(grid, visited, i, j);
}
}
}
cout << result << '\n';
return 0;
}为什么要在入队时标记?
同一块陆地可能被多个已访问邻居同时发现。入队时立即标记,可以防止它被反复加入队列,保证每块陆地最多入队一次。这里的队列用于遍历连通块,不需要为了统计岛屿再记录层数;可联系 BFS 理论基础复习。
- 时间复杂度:
- 空间复杂度:最坏 ,包括访问标记与队列
示例推演:
输入:
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 14 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1| 首次发现的未访问陆地(下标从 0 开始) | 本次标记的岛屿 | 累计岛屿数 |
|---|---|---|
(0, 0) | 左上角相连的四块陆地 | 1 |
(2, 2) | 中间单独一块陆地 | 2 |
(3, 3) | 右下角水平相连的两块陆地 | 3 |
输出为 3。(2, 2) 与 (3, 3) 只是对角线相邻,所以不属于同一座岛。
DFS / BFS 与边界情况速查:
| 对比项 | DFS | BFS |
|---|---|---|
| 搜索方式 | 沿一个方向深入,再返回继续搜索 | 用队列逐层扩展 |
| 标记时机 | 进入递归函数时,先标记当前陆地 | 入队前标记起点或邻居 |
| 是否撤销访问标记 | 不撤销 | 不撤销 |
| 额外容器 | 递归调用栈 | 队列 |
| 本题统计结果 | 陆地连通块数量 | 陆地连通块数量 |
- 全部是水域:答案为
0。 - 非空网格全部是陆地:答案为
1。 - 单行、单列或单个陆地:仍按四方向连通规则处理。
- 接触网格边界的岛屿:仍然计数,不要额外排除边界陆地。
- 两份实现均使用独立的
visited,不修改原始网格;主循环扫描全图,不会遗漏与其他区域不连通的岛屿。
2026-11-08(周日)
图论(四)
五、岛屿的最大面积
参考:代码随想录题解
网格中 1 表示陆地、0 表示水域,上下左右相邻的陆地组成一座岛。求所有岛屿中最大的陆地格子数,没有陆地时返回 0。输入先给出行数、列数,再给出整数网格,最后输出最大面积;题目行数、列数均不超过 50。
与岛屿数量的区别是:遇到新连通块时,不是把总答案加 1,而是完整统计这座岛的面积,再更新全局最大值。
统一思路:扫描全图 → 遇到未访问陆地 → 统计当前岛屿面积 → 更新最大值。visited 在整张图上共享,不在每座岛开始时清空;只有当前岛屿的面积需要重新计数。
方法一:DFS 处理当前节点
进入函数后,若当前格子是水域或已经访问则返回;否则先标记并累加当前格子,再搜索四个方向。因为起点也由 DFS 负责计数,外层将当前面积初始化为 0。使用引用参数 area 代替全局计数器,使每座岛的统计状态更明确。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y, int& area) {
if (grid[x][y] == 0 || visited[x][y]) {
return;
}
visited[x][y] = true;
++area;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
dfs(grid, visited, nextX, nextY, area);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
int area = 0;
dfs(grid, visited, i, j, area);
result = max(result, area);
}
}
}
cout << result << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y, int& area) {
if (grid[x][y] == 0 || visited[x][y]) {
return;
}
visited[x][y] = true;
++area;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
dfs(grid, visited, nextX, nextY, area);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
int area = 0;
dfs(grid, visited, i, j, area);
result = max(result, area);
}
}
}
cout << result << '\n';
return 0;
}方法二:DFS 只处理相邻节点
这种写法约定:当前格子已经由调用者计数、标记,函数只负责发现和处理新的邻居。因此外层必须先设 area = 1,并标记起点;递归前也先对新邻居计数、标记。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y, int& area) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1 && !visited[nextX][nextY]) {
visited[nextX][nextY] = true;
++area;
dfs(grid, visited, nextX, nextY, area);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
int area = 1;
visited[i][j] = true;
dfs(grid, visited, i, j, area);
result = max(result, area);
}
}
}
cout << result << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y, int& area) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1 && !visited[nextX][nextY]) {
visited[nextX][nextY] = true;
++area;
dfs(grid, visited, nextX, nextY, area);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
int area = 1;
visited[i][j] = true;
dfs(grid, visited, i, j, area);
result = max(result, area);
}
}
}
cout << result << '\n';
return 0;
}两种 DFS 的起点计数约定不能混用
第一种由函数处理当前格子,外层从
0开始;第二种由调用者先处理当前格子,外层从1开始。混用会导致起点被漏计或重复计数。两种写法都要做到每块陆地只计一次,且访问标记不回溯撤销。
方法三:BFS 入队时累计面积
起点入队前先标记,面积从 1 开始;每发现一块未访问陆地,就立即标记、累计面积并入队。使用 queue<pair<int, int>> 将行列坐标作为一组保存,避免用两个连续整数维护坐标时发生配对错误。
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int bfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
int area = 1;
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != 1 || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
++area;
que.push({nextX, nextY});
}
}
return area;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
result = max(result, bfs(grid, visited, i, j));
}
}
}
cout << result << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int bfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
visited[x][y] = true;
que.push({x, y});
int area = 1;
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] != 1 || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
++area;
que.push({nextX, nextY});
}
}
return area;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1 && !visited[i][j]) {
result = max(result, bfs(grid, visited, i, j));
}
}
}
cout << result << '\n';
return 0;
}三种实现都不修改原始网格,且复杂度相同:
- 时间复杂度:,每块陆地只处理一次,每次检查四个方向。
- 空间复杂度:最坏 ,包括访问标记与递归栈或队列。递归 DFS 的最坏深度也可能达到 ,大规模网格可优先考虑迭代实现。
六、孤岛的总面积
参考:代码随想录题解
只统计整座岛都不与网格边界相连的陆地总面积,不是求孤岛的数量,也不是只取其中最大一座。相邻仍指上下左右;题目行数、列数均不超过 50。
逆向思路:先排除与边界连通的陆地
- 扫描最左、最右、最上、最下四条边,遇到陆地就启动搜索。
- 将该位置以及与它连通的整块陆地都改为
0,等价于删除所有不能计入答案的岛屿。 - 边界处理完后,剩下的
1都属于孤岛,遍历全图累计其数量即可。
不是只删除边界那一圈陆地
某块陆地即使位于矩阵内部,只要能沿其他陆地走到边界,仍不属于孤岛,必须随整个连通块一起排除。反过来,只与边界陆地对角线相邻,不构成四方向连通,不应被误删。
方法一:DFS 从边界向内部清除
进入搜索函数时先把当前陆地改成 0,再访问相邻的 1。这个修改同时充当访问标记,不需要另建 visited。
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(vector<vector<int>>& grid, int x, int y) {
grid[x][y] = 0;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
dfs(grid, nextX, nextY);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
cout << 0 << '\n';
return 0;
}
for (int i = 0; i < rows; ++i) {
if (grid[i][0] == 1) {
dfs(grid, i, 0);
}
if (grid[i][cols - 1] == 1) {
dfs(grid, i, cols - 1);
}
}
for (int j = 0; j < cols; ++j) {
if (grid[0][j] == 1) {
dfs(grid, 0, j);
}
if (grid[rows - 1][j] == 1) {
dfs(grid, rows - 1, j);
}
}
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result += grid[i][j];
}
}
cout << result << '\n';
return 0;
}#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void dfs(vector<vector<int>>& grid, int x, int y) {
grid[x][y] = 0;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
dfs(grid, nextX, nextY);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
cout << 0 << '\n';
return 0;
}
for (int i = 0; i < rows; ++i) {
if (grid[i][0] == 1) {
dfs(grid, i, 0);
}
if (grid[i][cols - 1] == 1) {
dfs(grid, i, cols - 1);
}
}
for (int j = 0; j < cols; ++j) {
if (grid[0][j] == 1) {
dfs(grid, 0, j);
}
if (grid[rows - 1][j] == 1) {
dfs(grid, rows - 1, j);
}
}
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result += grid[i][j];
}
}
cout << result << '\n';
return 0;
}方法二:BFS 从边界向内部清除
起点与每个新发现的邻居都在入队前改为 0,防止重复入队。外层边界扫描和最终面积统计与 DFS 版本相同。
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void bfs(vector<vector<int>>& grid, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
grid[x][y] = 0;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
grid[nextX][nextY] = 0;
que.push({nextX, nextY});
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
cout << 0 << '\n';
return 0;
}
for (int i = 0; i < rows; ++i) {
if (grid[i][0] == 1) {
bfs(grid, i, 0);
}
if (grid[i][cols - 1] == 1) {
bfs(grid, i, cols - 1);
}
}
for (int j = 0; j < cols; ++j) {
if (grid[0][j] == 1) {
bfs(grid, 0, j);
}
if (grid[rows - 1][j] == 1) {
bfs(grid, rows - 1, j);
}
}
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result += grid[i][j];
}
}
cout << result << '\n';
return 0;
}#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
void bfs(vector<vector<int>>& grid, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
queue<pair<int, int>> que;
grid[x][y] = 0;
que.push({x, y});
while (!que.empty()) {
auto current = que.front();
que.pop();
for (const auto& direction : directions) {
int nextX = current.first + direction[0];
int nextY = current.second + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
grid[nextX][nextY] = 0;
que.push({nextX, nextY});
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
cout << 0 << '\n';
return 0;
}
for (int i = 0; i < rows; ++i) {
if (grid[i][0] == 1) {
bfs(grid, i, 0);
}
if (grid[i][cols - 1] == 1) {
bfs(grid, i, cols - 1);
}
}
for (int j = 0; j < cols; ++j) {
if (grid[0][j] == 1) {
bfs(grid, 0, j);
}
if (grid[rows - 1][j] == 1) {
bfs(grid, rows - 1, j);
}
}
int result = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result += grid[i][j];
}
}
cout << result << '\n';
return 0;
}重复扫描角点不会重复搜索,但修改网格需要说明
角点或单行、单列中的格子可能被边界循环检查多次,但首次搜索后已变成
0,后续会跳过。两种清除实现都会修改原网格;若后续还需要原数据,应先复制网格。没有单独的visited不代表额外空间为常数,递归栈或队列仍需空间。
- 时间复杂度:,边界检查、陆地清除和最后统计的总工作量为线性。
- 辅助空间复杂度:最坏 ,DFS 为递归栈,BFS 为队列,不额外建立访问表。
- 单行、单列或非空网格全部为陆地时,所有陆地都与边界相连,孤岛总面积为
0;全部为水域时也为0。
同一网格下,三类岛屿问题的答案不同:
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 14 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1三座岛的面积分别为 4、1、2。左上角和右下角的岛屿接触边界,只有 (2, 2)(下标从 0 开始)的单块陆地是孤岛。
| 对比项 | 岛屿数量 | 岛屿的最大面积 | 孤岛的总面积 |
|---|---|---|---|
| 统计目标 | 所有陆地连通块的个数 | 最大连通块的陆地格子数 | 所有不与边界连通的陆地格子总数 |
| 汇总方式 | 发现新连通块,答案 + 1 | 每个连通块计算面积后取最大值 | 排除边界连通块,再累加剩余陆地 |
| 是否计入边界岛屿 | 是 | 是 | 否 |
| 上述示例答案 | 3 | 4 | 1 |
2026-11-09(周一)
图论(五)
七、水流问题
给定高度矩阵,水可以向上下左右更低或等高的相邻格子流动。第一组边界是上边界、左边界,第二组边界是下边界、右边界,找出能流向两组边界的位置。
- 输入先给出行数、列数,再给出高度矩阵;题目行数、列数均不超过
100。 - 输出符合条件的坐标,每行一个
行下标 列下标,下标从0开始,顺序不限。 - “能流向两组边界”表示存在通往第一组的路径,也存在通往第二组的路径;两条路径可以不同,不要求沿同一条路径依次经过两组边界。
方法一:从每个格子出发,顺流搜索
这是最直观的思路:枚举一个起点,沿不升高的方向搜索所有可达格子,再判断访问集合是否与两组边界都相交。每个起点的 visited 必须重新建立,因为不同起点的可达范围不同。
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{-1, 0}, {0, -1}, {1, 0}, {0, 1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
if (visited[x][y]) {
return;
}
visited[x][y] = true;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] > grid[x][y]) {
continue; // 顺流:不能从低处流向高处
}
dfs(grid, visited, nextX, nextY);
}
}
bool canReachBoth(const vector<vector<int>>& grid, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
dfs(grid, visited, x, y);
bool reachesFirst = false;
bool reachesSecond = false;
for (int i = 0; i < rows; ++i) {
reachesFirst = reachesFirst || visited[i][0];
reachesSecond = reachesSecond || visited[i][cols - 1];
}
for (int j = 0; j < cols; ++j) {
reachesFirst = reachesFirst || visited[0][j];
reachesSecond = reachesSecond || visited[rows - 1][j];
}
return reachesFirst && reachesSecond;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (canReachBoth(grid, i, j)) {
cout << i << ' ' << j << '\n';
}
}
}
return 0;
}#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{-1, 0}, {0, -1}, {1, 0}, {0, 1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
if (visited[x][y]) {
return;
}
visited[x][y] = true;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] > grid[x][y]) {
continue; // 顺流:不能从低处流向高处
}
dfs(grid, visited, nextX, nextY);
}
}
bool canReachBoth(const vector<vector<int>>& grid, int x, int y) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
dfs(grid, visited, x, y);
bool reachesFirst = false;
bool reachesSecond = false;
for (int i = 0; i < rows; ++i) {
reachesFirst = reachesFirst || visited[i][0];
reachesSecond = reachesSecond || visited[i][cols - 1];
}
for (int j = 0; j < cols; ++j) {
reachesFirst = reachesFirst || visited[0][j];
reachesSecond = reachesSecond || visited[rows - 1][j];
}
return reachesFirst && reachesSecond;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (canReachBoth(grid, i, j)) {
cout << i << ' ' << j << '\n';
}
}
}
return 0;
}- 时间复杂度:最坏 ,共有
R * C个起点,每个起点都可能搜索全图,且重复初始化访问表。 - 辅助空间复杂度:,每次搜索的访问表与递归栈可复用空间,不需要同时保存所有起点的访问表。
- 适合用来理解题意、对拍小规模数据;大规模重复搜索容易超时。
方法二:从两组边界出发,逆流搜索(推荐)
不再逐个询问“这个格子能流到哪里”,而是改问“哪些格子能够流到这组边界”。
若顺流路径中有一步 u → v,则 height[u] >= height[v]。将这一步反过来,从 v 寻找可能的来源 u,就必须满足 height[u] >= height[v],即逆向搜索时,下一格必须更高或等高。
- 建立
firstBorder,表示能顺流到达第一组边界的格子。从上边界、左边界的所有格子作为起点,逆流搜索并标记。 - 建立独立的
secondBorder,表示能顺流到达第二组边界的格子。从下边界、右边界作为起点,同样逆流搜索。 - 同一组边界的所有起点共享一张访问表,不用每启动一个边界格子就清空;这样每个格子在每组搜索中最多标记一次。
- 扫描全图,输出
firstBorder[i][j] && secondBorder[i][j]的坐标,也就是两个可达集合的交集。
#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{-1, 0}, {0, -1}, {1, 0}, {0, 1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
if (visited[x][y]) {
return;
}
visited[x][y] = true;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] < grid[x][y]) {
continue; // 逆流:只能走向更高或等高的位置
}
dfs(grid, visited, nextX, nextY);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
return 0;
}
vector<vector<bool>> firstBorder(rows, vector<bool>(cols, false));
vector<vector<bool>> secondBorder(rows, vector<bool>(cols, false));
// 左边界属于第一组,右边界属于第二组。
for (int i = 0; i < rows; ++i) {
dfs(grid, firstBorder, i, 0);
dfs(grid, secondBorder, i, cols - 1);
}
// 上边界属于第一组,下边界属于第二组。
for (int j = 0; j < cols; ++j) {
dfs(grid, firstBorder, 0, j);
dfs(grid, secondBorder, rows - 1, j);
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (firstBorder[i][j] && secondBorder[i][j]) {
cout << i << ' ' << j << '\n';
}
}
}
return 0;
}#include <iostream>
#include <vector>
using namespace std;
const int directions[4][2] = {
{-1, 0}, {0, -1}, {1, 0}, {0, 1}
};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited,
int x, int y) {
if (visited[x][y]) {
return;
}
visited[x][y] = true;
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] < grid[x][y]) {
continue; // 逆流:只能走向更高或等高的位置
}
dfs(grid, visited, nextX, nextY);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
if (rows == 0 || cols == 0) {
return 0;
}
vector<vector<bool>> firstBorder(rows, vector<bool>(cols, false));
vector<vector<bool>> secondBorder(rows, vector<bool>(cols, false));
// 左边界属于第一组,右边界属于第二组。
for (int i = 0; i < rows; ++i) {
dfs(grid, firstBorder, i, 0);
dfs(grid, secondBorder, i, cols - 1);
}
// 上边界属于第一组,下边界属于第二组。
for (int j = 0; j < cols; ++j) {
dfs(grid, firstBorder, 0, j);
dfs(grid, secondBorder, rows - 1, j);
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (firstBorder[i][j] && secondBorder[i][j]) {
cout << i << ' ' << j << '\n';
}
}
}
return 0;
}高度条件要反转,但“等高可以流动”不能丢掉
顺流时允许
nextHeight <= currentHeight;逆流时允许nextHeight >= currentHeight。两者都包含等高,不能改成严格不等。等高格子之间可能形成环,必须在继续搜索邻居前标记当前格子,避免无限递归。
共享访问表的范围是一组边界,而不是两组边界
第一组内部共享
firstBorder,第二组内部共享secondBorder,两张表相互独立。若把两组混成一张表,只能知道格子能否到达某一组,无法判断是否两组都能到达。角点被同一组重复检查时,访问标记会使其立即返回,不会反复展开整个区域。
- 时间复杂度:,每组搜索最多完整展开每个格子一次,再扫描全图取交集。
- 辅助空间复杂度:最坏 ,包括两张访问表和递归栈。
示例推演:
3 3
1 2 3
2 3 4
3 4 53 3
1 2 3
2 3 4
3 4 5| 行下标 | 高度 | firstBorder:能流向上 / 左边界 | secondBorder:能流向下 / 右边界 |
|---|---|---|---|
| 0 | [1, 2, 3] | [true, true, true] | [false, false, true] |
| 1 | [2, 3, 4] | [true, true, true] | [false, false, true] |
| 2 | [3, 4, 5] | [true, true, true] | [true, true, true] |
所有格子都能顺流向上或向左,但只有最右列、最下行能到达第二组边界。按行优先输出交集:
0 2
1 2
2 0
2 1
2 20 2
1 2
2 0
2 1
2 2两种思路与边界速查:
| 对比项 | 每个格子顺流搜索 | 两组边界逆流搜索 |
|---|---|---|
| 出发位置 | 全图每个格子分别作为起点 | 每组边界作为一组起点 |
| 允许的下一格高度 | 小于或等于当前高度 | 大于或等于当前高度 |
| 访问表使用方式 | 每个起点重新建立 | 同组共享,两组独立 |
| 最坏时间复杂度 | ||
| 最终判断 | 单个起点的可达集合是否碰到两组边界 | 两组标记在当前位置是否都为 true |
- 起点本身位于某组边界,就已经能到达该组,不要求至少移动一步。右上角、左下角同时属于两组边界,所以一定满足条件。
- 单行或单列网格中,每个格子都同时接触两组边界,因此全部输出;全图等高时,也应输出全部格子。
- 两种代码均保留原高度矩阵。不要照搬岛屿题中“将访问位置改为
0”的标记方式,否则会破坏后续流向判断;高度为0也不能直接当成障碍。 - 本题求的是可达性,不是最短路,也不是枚举所有路径。访问标记不需要回溯撤销;较大网格中若递归栈受限,可以用显式栈或多源 BFS 实现同样的逆向搜索。
2026-11-10(周二)
图论(六)
八、建造最大岛屿
给定由 1(陆地)和 0(水域)组成的网格,最多将一个 0 改成 1,求操作后最大的岛屿面积。连通仍只考虑上下左右,不包括对角线;题目行数、列数均不超过 50。
输入先给出行数、列数,再给出整数网格,输出一个最大面积值。与岛屿的最大面积相比,本题允许新添一块陆地,将它四周原本分离的岛屿连接起来。
暴力思路与重复计算:
可以枚举每个水格,临时改成陆地,再搜索全图计算最大岛屿面积;每次尝试后恢复原值。若对每个候选都重新搜索,最坏时间为 。原有岛屿内部的连通关系没有改变,重复求面积是不必要的。
优化:先编号,再枚举合并
- 预处理原有岛屿:扫描网格,对每块尚未处理的陆地启动一次 DFS,统计面积,并把整座岛改写为同一个编号。编号从
2开始,避免与水域0、尚未处理的陆地1冲突。 - 记录编号与面积:
islandArea[id]表示编号为id的岛屿面积。第一阶段同时记录原有最大面积,覆盖“最多翻转一次,也可以不翻转”的情况。 - 枚举水格作为新陆地:当前候选面积从
1开始,代表新添加的这一格;查看上下左右,把相邻岛屿的面积加上。 - 按岛屿编号去重:一个水格可能从多个方向接触同一座岛,必须只加一次。为每个候选水格单独创建一个集合,记录已经加入的岛屿编号。
- 更新全局最大值:第二阶段只计算假想翻转后的面积,不真正把水格改成陆地,也不再次运行 DFS。
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int dfs(vector<vector<int>>& grid, int x, int y, int id) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
grid[x][y] = id;
int area = 1;
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
area += dfs(grid, nextX, nextY, id);
}
}
return area;
}
int largestIsland(vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
unordered_map<int, int> islandArea;
int nextId = 2;
int result = 0;
// 第一阶段:为每座原有岛屿编号,并记录面积。
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1) {
int area = dfs(grid, i, j, nextId);
islandArea[nextId] = area;
result = max(result, area);
++nextId;
}
}
}
// 第二阶段:枚举一个水格,合并相邻且编号不同的岛屿。
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 0) {
continue;
}
int candidate = 1;
unordered_set<int> adjacentIds;
for (const auto& direction : directions) {
int nextX = i + direction[0];
int nextY = j + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
int id = grid[nextX][nextY];
if (id < 2) {
continue; // 水域不是岛屿,不查询其面积。
}
if (adjacentIds.insert(id).second) {
candidate += islandArea.at(id);
}
}
result = max(result, candidate);
}
}
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << largestIsland(grid) << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int dfs(vector<vector<int>>& grid, int x, int y, int id) {
int rows = static_cast<int>(grid.size());
int cols = static_cast<int>(grid[0].size());
grid[x][y] = id;
int area = 1;
for (const auto& direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
if (grid[nextX][nextY] == 1) {
area += dfs(grid, nextX, nextY, id);
}
}
return area;
}
int largestIsland(vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
unordered_map<int, int> islandArea;
int nextId = 2;
int result = 0;
// 第一阶段:为每座原有岛屿编号,并记录面积。
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1) {
int area = dfs(grid, i, j, nextId);
islandArea[nextId] = area;
result = max(result, area);
++nextId;
}
}
}
// 第二阶段:枚举一个水格,合并相邻且编号不同的岛屿。
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 0) {
continue;
}
int candidate = 1;
unordered_set<int> adjacentIds;
for (const auto& direction : directions) {
int nextX = i + direction[0];
int nextY = j + direction[1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) {
continue;
}
int id = grid[nextX][nextY];
if (id < 2) {
continue; // 水域不是岛屿,不查询其面积。
}
if (adjacentIds.insert(id).second) {
candidate += islandArea.at(id);
}
}
result = max(result, candidate);
}
}
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << largestIsland(grid) << '\n';
return 0;
}去重的是岛屿编号,不是面积,也不是相邻格子的坐标
四个邻居可能属于同一座岛,也可能属于面积相同的不同岛。只有编号能区分连通块。
adjacentIds必须针对每个候选水格重新建立,不能跨候选共用未清空的集合。
编号可以直接充当访问标记
DFS 进入陆地后立即把
1改成编号,后续只搜索仍为1的邻居,因此不需要额外的visited。水格0不参与面积查询;代码使用at(id)读取已记录的面积,避免用operator[]查询水域或未知编号时意外插入默认项。
示例推演:
3 3
1 0 1
1 0 1
0 1 03 3
1 0 1
1 0 1
0 1 0第一遍编号后,网格为:
2 0 3
2 0 3
0 4 02 0 3
2 0 3
0 4 0| 岛屿编号 | 面积 | 原网格中的位置(下标从 0 开始) |
|---|---|---|
| 2 | 2 | (0,0)、(1,0) |
| 3 | 2 | (0,2)、(1,2) |
| 4 | 1 | (2,1) |
- 翻转
(0,1),连接编号2、3,面积为1 + 2 + 2 = 5。 - 翻转
(1,1),连接编号2、3、4,面积为1 + 2 + 2 + 1 = 6,是本例最优答案。 - 编号
2、3的面积虽然相同,但它们是不同岛屿,不能因为面积相同而去重。
同一座岛被多次接触的情况:对于中心为 0、其余八格均为 1 的 3 × 3 网格,中心四周都属于同一个编号。翻转中心后应算 1 + 8 = 9,不能把面积 8 加四次。
为什么只看四个邻居就够了?
新增的一格只能通过它的四个邻居接入原有岛屿;被接入岛屿的整块面积已预先记录。对不同邻居编号的面积求和,就恰好得到包含新增格子的连通块面积,再与原有最大岛屿比较,便覆盖了所有“最多翻转一格”的可能。
边界情况与实现约定:
| 情况 | 处理结果 |
|---|---|
| 全部是陆地 | 第一阶段已记录总面积,第二阶段没有水格,直接保留该结果 |
| 非空网格全部是水域 | 任意水格翻转后面积为 1 |
| 单个格子 | 原来为 0 或 1,最终答案均为 1 |
| 新陆地与多个方向的同一岛屿相邻 | 同一编号只累加一次 |
| 只有对角线接触 | 不直接连接,必须通过上下左右的陆地路径连接 |
- 第一阶段会把原网格中的陆地改成编号;若后续仍需使用原始
0/1数据,或想再次对同一份原始输入调用函数,应先复制网格。 - 两个阶段的行列增量都统一使用
direction[0]、direction[1],不要混淆行下标与列下标。 - 时间复杂度:平均 ,每块原陆地只编号一次,每个水格检查四个方向;哈希操作按平均 计算。
- 辅助空间复杂度:最坏 ,包括岛屿面积表和递归栈;单个候选的相邻编号集合最多有四个元素,为 大小。大网格若递归栈受限,可用显式栈或 BFS 完成编号。
2026-11-11(周三)
图论(七)
九、岛屿的周长
给定由 1(陆地)和 0(水域)组成的网格,每个格子的边长为 1,求岛屿的周长。题目保证恰好一座岛屿,且岛屿内部没有水域;矩阵外视为水域,陆地只通过上下左右相连。行数、列数均在 1~50 之间。
输入先给出行数、列数,再给出整数网格,输出一个周长值。
解法一:逐块陆地检查四条边
- 遍历每个格子,跳过水域,只处理陆地。
- 对当前陆地检查上下左右四个方向。
- 如果邻居越界,说明这一侧接触矩阵外的水域,周长加
1。 - 如果邻居在网格内且为水域,周长也加
1;相邻格为陆地时,这条边属于内部共享边,不计入周长。
#include <iostream>
#include <vector>
using namespace std;
int islandPerimeter(const vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int perimeter = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 1) {
continue;
}
for (const auto& direction : directions) {
int nextX = i + direction[0];
int nextY = j + direction[1];
if (nextX < 0 || nextX >= rows ||
nextY < 0 || nextY >= cols ||
grid[nextX][nextY] == 0) {
++perimeter;
}
}
}
}
return perimeter;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << islandPerimeter(grid) << '\n';
return 0;
}#include <iostream>
#include <vector>
using namespace std;
int islandPerimeter(const vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
const int directions[4][2] = {
{0, 1}, {1, 0}, {-1, 0}, {0, -1}
};
int perimeter = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 1) {
continue;
}
for (const auto& direction : directions) {
int nextX = i + direction[0];
int nextY = j + direction[1];
if (nextX < 0 || nextX >= rows ||
nextY < 0 || nextY >= cols ||
grid[nextX][nextY] == 0) {
++perimeter;
}
}
}
}
return perimeter;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << islandPerimeter(grid) << '\n';
return 0;
}先判断越界,再访问网格
||从左到右短路求值:只要任意越界条件成立,就不会执行最后的grid[nextX][nextY]。不要把数组访问放到越界检查前面。矩阵边缘的陆地同样会贡献周长,不能只统计网格内部的陆地与水域交界。
解法二:陆地格数乘四,减去共享边
设陆地格子总数为 ,上下或左右相邻的无序陆地对数为 ,则:
- 先把每个陆地格都看成独立正方形,一共有
4 * L条边。 - 每对相邻陆地共享一条边;这条边在两个格子中各被算了一次,但不属于周长,因此应减去
2。 - 扫描时只检查上方、左方,每对相邻陆地恰好计数一次;也可以统一改成只检查下方、右方。
这里统计的是陆地格数,不是岛屿数量
原笔记中的“岛屿数量 × 4”应改为“陆地格子数量 × 4”。一座岛可以包含很多陆地格;
E则是共享边数量,不是“有相邻陆地的格子数量”。
#include <iostream>
#include <vector>
using namespace std;
int islandPerimeter(const vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
int landCount = 0;
int sharedEdges = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 1) {
continue;
}
++landCount;
if (i > 0 && grid[i - 1][j] == 1) {
++sharedEdges;
}
if (j > 0 && grid[i][j - 1] == 1) {
++sharedEdges;
}
}
}
return 4 * landCount - 2 * sharedEdges;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << islandPerimeter(grid) << '\n';
return 0;
}#include <iostream>
#include <vector>
using namespace std;
int islandPerimeter(const vector<vector<int>>& grid) {
int rows = static_cast<int>(grid.size());
if (rows == 0 || grid[0].empty()) {
return 0;
}
int cols = static_cast<int>(grid[0].size());
int landCount = 0;
int sharedEdges = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != 1) {
continue;
}
++landCount;
if (i > 0 && grid[i - 1][j] == 1) {
++sharedEdges;
}
if (j > 0 && grid[i][j - 1] == 1) {
++sharedEdges;
}
}
}
return 4 * landCount - 2 * sharedEdges;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<vector<int>> grid(rows, vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> grid[i][j];
}
}
cout << islandPerimeter(grid) << '\n';
return 0;
}共享边不能重复扣除
当前公式
4 * landCount - 2 * sharedEdges的前提是每条共享边只统计一次。若检查全部四个方向,每条共享边会被统计两次,此时再乘2就会多减。两块左右相邻的陆地应得到8 - 2 = 6,不是8 - 4 = 4。
示例推演:
5 5
0 0 0 0 0
0 1 0 1 0
0 1 1 1 0
0 1 1 1 0
0 0 0 0 05 5
0 0 0 0 0
0 1 0 1 0
0 1 1 1 0
0 1 1 1 0
0 0 0 0 0| 统计项 | 数量 | 说明 |
|---|---|---|
| 陆地格子 | 8 | 不是岛屿数量 1 |
| 水平方向共享边 | 4 | 中间两行各有两条 |
| 竖直方向共享边 | 5 | 相邻的陆地行之间分别有两条、三条 |
| 总共享边 | 9 | 每条只计一次 |
| 周长 | 14 | 4 * 8 - 2 * 9 |
两种解法都会输出 14:第一种直接累加暴露边,第二种先算所有格子的边,再剔除内部共享边。
边界情况与适用范围:
| 情况 | 周长 / 处理方式 |
|---|---|
| 单个陆地格 | 4 |
| 两个水平或竖直相邻的陆地格 | 6 |
一条连续的 k 格陆地 | 2 * k + 2 |
R × C 网格全部为陆地 | 2 * R + 2 * C |
| 陆地接触矩阵边缘 | 越界的一侧也要计入周长 |
| 只在对角线接触(扩展情形) | 不共享边,两个独立陆地格总周长为 8 |
- 两种实现都不修改网格,且不需要
visited、递归栈或队列。 - 时间复杂度均为 ;除输入网格外,额外空间均为 ,若计入保存输入的空间则为 。
- 题目保证恰好一座岛且内部无水域。扩展到多座岛时,这两种写法会计算所有陆地的总周长,不是某一座岛的周长;全水域则返回
0。 - 若允许岛内有湖,两种写法都会把湖岸线算进去。例如八格陆地围住中心水格的
3 × 3网格,结果为外边界12加内边界4,共16。若题目只要求与外部水域相邻的海岸线,需要先从网格外围搜索外部水域,不能直接套用本题的总边界计数。
2026-11-12(周四)
图论(八)
十、字符串接龙
从 beginStr 出发,每次只改变一个字符,最终到达 endStr。中间字符串必须来自字典 strList,且一条转换序列中不能重复使用同一个字典字符串。求最短转换序列中的字符串数量;无法到达则输出 0。题目给出的字典条目数为 2~500。
输入依次为字典条目数、起点与终点、字典中的各个字符串;只输出最短序列长度,不要求还原具体路径。本节沿用原代码的字符约定:字符串由小写英文字母组成,只做字符替换,不做插入或删除,因此有效路径上的字符串等长。
一、隐式建图:两个字符串如何连边?
- 节点:起点、终点以及可用的字典字符串。
- 边:两个等长字符串恰好有一个位置不同,就可以用一次替换相互转换。字符相同的两个字符串之间不算一次转换。
- 边权:每次转换的代价都相同,可以视为权重
1,因此是无权最短路问题。
不必预先两两比较所有字符串来建立邻接表。搜索一个节点时,依次选择每个位置,枚举替换为 'a'~'z' 中的其他字符,再查询生成的新字符串是否为终点或字典中的可用节点。这种搜索时才生成邻居的方式就是隐式建图。
二、用 BFS 按层搜索最短序列
与 BFS 理论与队列模板一样,队列中的节点按照距离从近到远展开:
- 起点入队,记录
distance[beginStr] = 1,因为起点本身也计入序列。 - 每次取出一个字符串,读取当前最短序列长度
currentLength。 - 枚举所有只替换一个字符的候选字符串,跳过替换后与原字符相同的情况。
- 如果候选就是终点,直接返回
currentLength + 1。 - 否则,只有字典中存在且从未访问过的候选才入队;入队时立即记录长度,同时完成访问标记。
- 队列耗尽仍未找到终点,返回
0。
本题终点不必出现在字典中
题目要求的是“中间字符串”来自字典。官方示例的
def不在字典里,但仍可以作为最后一个节点。因此要先判断nextWord == endStr,再检查字典成员资格;不能套用其他同类题中“终点不在字典就返回0”的规则。
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int shortestSequenceLength(const string& beginStr,
const string& endStr,
const unordered_set<string>& dictionary) {
if (beginStr == endStr) {
return 1; // 已经到达终点,序列只含起点。
}
if (beginStr.size() != endStr.size()) {
return 0; // 只允许替换字符,无法改变字符串长度。
}
queue<string> que;
unordered_map<string, int> distance; // 字符串 -> 最短序列中的节点数
que.push(beginStr);
distance.emplace(beginStr, 1);
while (!que.empty()) {
string word = que.front();
que.pop();
int currentLength = distance.at(word);
for (size_t i = 0; i < word.size(); ++i) {
string nextWord = word; // 每次更换位置时,从原字符串重新开始。
for (char ch = 'a'; ch <= 'z'; ++ch) {
if (ch == word[i]) {
continue; // 必须恰好改变一个字符。
}
nextWord[i] = ch;
if (nextWord == endStr) {
return currentLength + 1;
}
if (dictionary.find(nextWord) == dictionary.end()) {
continue;
}
if (distance.emplace(nextWord, currentLength + 1).second) {
que.push(nextWord); // 首次发现才记录并入队。
}
}
}
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
string beginStr, endStr;
cin >> beginStr >> endStr;
unordered_set<string> dictionary;
for (int i = 0; i < n; ++i) {
string word;
cin >> word;
dictionary.insert(word);
}
cout << shortestSequenceLength(beginStr, endStr, dictionary) << '\n';
return 0;
}#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int shortestSequenceLength(const string& beginStr,
const string& endStr,
const unordered_set<string>& dictionary) {
if (beginStr == endStr) {
return 1; // 已经到达终点,序列只含起点。
}
if (beginStr.size() != endStr.size()) {
return 0; // 只允许替换字符,无法改变字符串长度。
}
queue<string> que;
unordered_map<string, int> distance; // 字符串 -> 最短序列中的节点数
que.push(beginStr);
distance.emplace(beginStr, 1);
while (!que.empty()) {
string word = que.front();
que.pop();
int currentLength = distance.at(word);
for (size_t i = 0; i < word.size(); ++i) {
string nextWord = word; // 每次更换位置时,从原字符串重新开始。
for (char ch = 'a'; ch <= 'z'; ++ch) {
if (ch == word[i]) {
continue; // 必须恰好改变一个字符。
}
nextWord[i] = ch;
if (nextWord == endStr) {
return currentLength + 1;
}
if (dictionary.find(nextWord) == dictionary.end()) {
continue;
}
if (distance.emplace(nextWord, currentLength + 1).second) {
que.push(nextWord); // 首次发现才记录并入队。
}
}
}
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
string beginStr, endStr;
cin >> beginStr >> endStr;
unordered_set<string> dictionary;
for (int i = 0; i < n; ++i) {
string word;
cin >> word;
dictionary.insert(word);
}
cout << shortestSequenceLength(beginStr, endStr, dictionary) << '\n';
return 0;
}为什么第一次找到终点就可以返回?
BFS 先展开序列长度为 1 的节点,再展开长度为 2、3……的节点。由长度为 d 的节点生成终点时,得到长度 d + 1 的序列;若存在更短序列,它的倒数第二个节点应已在更早的层被展开,终点也就会更早被发现。因此第一次生成终点即可返回最短值。
求最短路与枚举所有路径的访问标记不同
本题只求最短长度,同一个字符串第一次入队时就已经确定了它的最短长度,后续重复到达不会更优,可以全局保留访问标记,不必在出队后删除。最短路径也不需要绕环重复使用节点,因此这种剪枝不会漏掉最优解。
与所有可达路径的回溯枚举不同,本题不需要保存每条路径,也不需要撤销访问状态。
示例推演:
6
abc def
efc
dbc
ebc
dec
dfc
yhn6
abc def
efc
dbc
ebc
dec
dfc
yhn| BFS 层次 | 本层首次发现的字符串(不强调队列内次序) | 对应序列长度 |
|---|---|---|
| 起点 | abc | 1 |
| 替换一次 | dbc、ebc | 2 |
| 替换两次 | dec、dfc、efc | 3 |
| 首次到达终点 | def | 4 |
例如一条最短序列是 abc → dbc → dec → def,所以输出 4。它经过 4 个字符串、3 次转换;题目要求前者,不是边数。示例中的 yhn 无法从起点到达,不影响结果。
易错点与边界情况:
| 情况 | 处理方式 |
|---|---|
| 起点与终点相同 | 按本实现约定直接返回 1,不必进行替换 |
| 起点与终点只差一个字符 | 返回 2,即使终点不在字典中 |
| 字典含起点、重复条目或存在环 | 集合去重,起点预先标记,每个可达字符串最多入队一次 |
| 没有合法转换序列 | 队列耗尽后返回 0 |
| 起点与终点长度不同 | 仅替换无法到达,返回 0 |
distance同时承担访问标记和长度记录的作用;emplace(...).second为真时才表示首次插入。- 每个字符位置都从
word复制出候选,再在该位置尝试不同字母,避免意外同时修改多个位置。若改成在同一个字符串上反复修改,换位置前必须恢复原字符。 - 不使用
distance[nextWord]来判断是否访问过,因为operator[]会在键不存在时插入默认值;查找可用find,这里直接用emplace判断首次访问。 - 本实现只枚举小写英文字母。若题目字符集不同,需要调整枚举范围;不能把“26 个字母”当成所有字符串问题都适用的规则。
复杂度分析:
设字典去重后有 个字符串,有效字符串长度为 ,字符集大小为 。讨论所有输入字符串均长为 的常见情形:
- 最多展开 个节点(字典节点和额外的起点),每个节点生成至多 个候选。
- 若把一次字符串哈希、比较视为常数操作,可简写为平均 ;但普通
std::string的哈希和最坏比较需要 ,计入字符串处理成本后,平均时间为 ,其中假设哈希桶查找平均高效。 - 字典、访问表与队列存储的字符串总量为 ;搜索辅助空间最坏也为 。这里没有显式存储两两连边,也没有保存完整路径。
2026-11-13(周五)
图论(九)
十一、有向图的完全联通
给定一个有向图,节点编号为 1~N,判断从节点 1 出发,能否沿有向边到达所有节点。全部可达输出 1,否则输出 -1。题目范围为 1 ≤ N ≤ 100、1 ≤ M ≤ 2000。
输入先给出节点数、边数,再给出每条边 s t,表示单向边 s → t。本题使用 M 表示边数,与题面中的 K 含义相同。
题目名称不等于“强连通”或“完全图”
本题只要求固定起点
1能到达所有节点,并不要求任意两个节点互相可达。例如1 → 2 → 3已经满足本题,但不是强连通图,也不是任意两个不同节点之间都有边的完全图。概念回顾见连通性与连通分量。
一、整体思路:搜索可达节点,不枚举所有路径
- 用邻接表保存每个节点的出边,只添加
graph[s].push_back(t),不能擅自添加反向边。 - 从节点
1开始运行一次 DFS,标记所有沿有向边可达的节点。 - 扫描
visited[1]~visited[N],只要有一个未访问的节点就输出-1;否则输出1。
这是一道单源可达性判断题,不是枚举所有可达路径。DFS、BFS 都可以完成遍历;本节保留两种 DFS 写法,重点比较“由谁负责标记节点”。不需要从每个节点重新搜索,也不需要记录路径或最短距离。
二、写法一:进入函数后处理当前节点
约定:调用 dfs(graph, u, visited) 时,u 可以尚未访问,也可以已经访问。
- 如果当前节点已经访问,立即返回,避免重复展开和沿环无限递归。
- 否则,先标记当前节点,再递归访问它的所有邻居。
- 主函数直接调用
dfs(graph, 1, visited),不需要提前标记起点。
#include <iostream>
#include <list>
#include <vector>
using namespace std;
void dfs(const vector<list<int>>& graph, int u, vector<bool>& visited) {
if (visited[u]) {
return;
}
visited[u] = true;
for (int v : graph[u]) {
dfs(graph, v, visited);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<list<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<bool> visited(n + 1, false);
dfs(graph, 1, visited);
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
cout << -1 << '\n';
return 0;
}
}
cout << 1 << '\n';
return 0;
}#include <iostream>
#include <list>
#include <vector>
using namespace std;
void dfs(const vector<list<int>>& graph, int u, vector<bool>& visited) {
if (visited[u]) {
return;
}
visited[u] = true;
for (int v : graph[u]) {
dfs(graph, v, visited);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<list<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<bool> visited(n + 1, false);
dfs(graph, 1, visited);
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
cout << -1 << '\n';
return 0;
}
}
cout << 1 << '\n';
return 0;
}这种写法可能对已访问的邻居调用 DFS,但这些调用会在入口立即返回;每个节点的邻接表仍只展开一次。
三、写法二:递归之前处理下一个节点
约定:进入 dfs(graph, u, visited) 时,当前节点 u 已经被调用方标记。函数只负责寻找未访问的邻居,先标记邻居,再递归展开。
- 主函数作为第一次调用的调用方,必须先设置
visited[1] = true。 - 循环中只对未访问的邻居递归,且必须在递归前标记。
- 不需要在函数入口重复写
if (visited[u]) return;没有未访问邻居时,循环自然结束,函数返回。
#include <iostream>
#include <list>
#include <vector>
using namespace std;
void dfs(const vector<list<int>>& graph, int u, vector<bool>& visited) {
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
dfs(graph, v, visited);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<list<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<bool> visited(n + 1, false);
visited[1] = true; // 起点也遵守“调用前已标记”的约定。
dfs(graph, 1, visited);
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
cout << -1 << '\n';
return 0;
}
}
cout << 1 << '\n';
return 0;
}#include <iostream>
#include <list>
#include <vector>
using namespace std;
void dfs(const vector<list<int>>& graph, int u, vector<bool>& visited) {
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
dfs(graph, v, visited);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<list<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<bool> visited(n + 1, false);
visited[1] = true; // 起点也遵守“调用前已标记”的约定。
dfs(graph, 1, visited);
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
cout << -1 << '\n';
return 0;
}
}
cout << 1 << '\n';
return 0;
}两种 DFS 约定对照:
| 对比项 | 写法一:处理当前节点 | 写法二:处理下一个节点 |
|---|---|---|
| 谁标记当前节点 | 当前 DFS 函数 | 调用当前函数的调用方 |
| 起点如何处理 | 直接调用,入口负责标记 | 主函数先标记,再调用 |
| 防止重复展开的位置 | 函数入口检查当前节点 | 循环中检查下一个节点 |
| 递归调用时机 | 可调用已访问节点,但立即返回 | 仅首次发现邻居时调用 |
| 停止方式 | 已访问时显式返回;循环结束也会返回 | 没有未访问邻居时自然返回 |
不能混用两种约定
写法二先标记邻居再递归,如果又在函数入口加上写法一的
if (visited[u]) return,每次进入都会立即返回,邻居的出边就不会展开;若起点也预先标记,则连起点都不会展开。反过来,采用写法二却忘记预先标记起点,也会破坏“进入函数时当前节点已访问”的约定,可能使起点一直未被标记。应整套采用同一种方式。
“没有显式终止判断”不等于递归不会终止
写法二在递归前检查并设置访问标记,每个节点最多被递归展开一次。即使图中有环、自环或重复边,已标记节点也不会再次递归。终止由邻居筛选与有限的未访问节点共同保证,而不是必须写一个独立的
return分支。
四、示例推演:
4 4
1 2
2 1
1 3
2 44 4
1 2
2 1
1 3
2 4按照输入的邻接表顺序,首次标记节点的顺序为 1 → 2 → 4 → 3:
- 标记
1,沿1 → 2到达2。 2 → 1指向已经访问的节点,不再展开,避免在环1 → 2 → 1中重复搜索。- 沿
2 → 4标记4,返回后继续搜索1的另一个邻居3。 - 最终
visited[1..4]全为true,输出1。
注意:上述顺序是 DFS 的首次访问顺序,不是一条经过所有节点的有向路径。本题允许从起点分别沿不同路线到达各节点,不要求存在一条连续路径依次经过全部节点。
五、易错点与复杂度:
- 不能把有向边当作无向边:若只有
2 → 1,不能由此认为1能到达2。 - 只从
1开始搜索:不能遇到未访问节点就再从它开始 DFS,然后用“全部已访问”判定成功;那样统计的是多个起点的搜索结果,不再代表从1可达。 - 标记不撤销:这里的
visited记录是否已经从起点到达,不是回溯中的“当前路径标记”,返回时不应恢复为false。 - 编号与数组范围一致:节点从
1开始,分配n + 1大小;最后只检查1~n,不检查未使用的下标0。节点1本身按零条边的路径视为可达。 - 避免无意义复制:直接使用
for (int v : graph[u])遍历原邻接表,不再像原代码那样先写list<int> keys = graph[u]复制整个链表;也用u、v区分当前节点与邻居,避免变量重名。 - BFS 也可实现:从
1入队并立即标记;每次取出节点,对未访问邻居先标记再入队,最后同样检查所有节点。相关模板见广度优先搜索理论基础。
| 边界或扩展情况 | 结果 / 处理方式 |
|---|---|
| 只有一个节点 | 起点自身可达,输出 1 |
存在从 1 无法到达的节点 | 输出 -1,即使该节点能反向到达 1 |
| 有环、自环或重复边 | 访问标记防止重复展开,不影响可达判断 |
从 1 分别到达不同分支 | 可以成功,不要求分支之间相互可达 |
| 无边图(题目范围外的扩展) | N = 1 输出 1,N > 1 输出 -1 |
- 两种写法的总时间复杂度均为 ,包括建图、搜索与最后的检查;可达节点的邻接表只展开一次。
- 保存邻接表需要 空间;除图以外,访问标记与最坏递归栈需要 辅助空间。若扩展到很深的大图,递归栈可能受限,可改用显式栈或 BFS。
2026-11-14(周六)
图论(十)
十二、并查集理论基础
并查集(Disjoint Set Union,DSU)维护若干个互不相交的集合,适合处理元素之间的分组、等价关系,以及无向图中不断加边时的连通性。
一、基本操作与表示方法
| 操作 | 含义 |
|---|---|
init(n) | 初始化,每个元素单独构成一个集合 |
find(u) | 返回元素 u 所在集合的代表,即根节点 |
isSame(u, v) | 判断两个元素的根是否相同 |
join(u, v) | 合并两个元素所在的整个集合,而不是只移动这两个元素 |
用 father[u] 记录节点 u 的父节点,所有集合共同构成一片父指针森林:
- 初始时
father[u] = u,每个元素都是自己的根。 - 根节点满足
father[root] == root,顺着父指针最终可以找到它。 - 两个元素属于同一集合,当且仅当
find(u) == find(v);父节点相同是充分条件,但不是必要条件,不能只比较father[u]与father[v]。 - 合并时先求两个根,再把一个根挂到另一个根上。直接修改非根节点可能只挪动部分子树,不能正确代表集合合并。
父指针不是原图中的有向边
father[rootV] = rootU只是集合内部的组织方式,不表示原图存在v → u,根编号也不一定是集合中的最小值。join(u, v)与join(v, u)可能产生不同的根,但合并后的成员关系相同。
二、优化一:路径压缩
普通寻根沿父指针不断向上走;若树退化成很长的链,查询会很慢。路径压缩在找到根后,让本次寻根路径上的节点直接指向根,减少后续重复查询的开销。
#include <vector>
using namespace std;
vector<int> father;
void init(int n) {
father.resize(n + 1); // 本节使用编号 1~n,下标 0 不参与业务。
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] == u) {
return u;
}
father[u] = find(father[u]); // 回溯时,把沿途节点直接连到根。
return father[u];
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false; // 已在同一集合,无须合并。
}
father[rootV] = rootU;
return true;
}#include <vector>
using namespace std;
vector<int> father;
void init(int n) {
father.resize(n + 1); // 本节使用编号 1~n,下标 0 不参与业务。
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] == u) {
return u;
}
father[u] = find(father[u]); // 回溯时,把沿途节点直接连到根。
return father[u];
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false; // 已在同一集合,无须合并。
}
father[rootV] = rootU;
return true;
}上面是仅使用路径压缩的独立模板片段,使用前调用 init(n)。join 的返回值表示是否真正合并了两个集合,普通连通性题可以忽略该返回值。
压缩过程示例:假设父指针为 4 → 3 → 2 → 1,且 father[1] = 1。调用 find(4) 返回 1,回溯后 father[4]、father[3]、father[2] 都变为 1。
一次查询不会自动压平整棵树
路径压缩只修改本次经过的节点,其他分支不会自动变成根的直接孩子;后续合并还可能使旧根挂到新根上。因此不能说“所有非根节点始终只需一步就能找到根”,也不能把每一次查询都当成严格的 。
三、优化二:按秩合并(先不做路径压缩)
让较矮的树挂到较高的树上,避免每次合并都把树变深。这里用 rankValue[root] 表示树高,按最长根到叶路径的边数计数,所以单节点的秩初始化为 0;原笔记初始化为 1 的写法则是按层数计数,两种约定都可以,但应保持一致。
- 两棵树秩不等时,较小秩的根挂到较大秩的根下,较大秩不变。
- 两棵树秩相等且根不同时,任选一棵作为新根,新根的秩加
1。 - 两个根相同时直接返回,不能重复增加秩。
#include <vector>
using namespace std;
vector<int> father;
vector<int> rankValue;
void init(int n) {
father.resize(n + 1);
rankValue.assign(n + 1, 0);
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] == u) {
return u;
}
return find(father[u]); // 为单独展示按秩合并,这里不做路径压缩。
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}#include <vector>
using namespace std;
vector<int> father;
vector<int> rankValue;
void init(int n) {
father.resize(n + 1);
rankValue.assign(n + 1, 0);
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] == u) {
return u;
}
return find(father[u]); // 为单独展示按秩合并,这里不做路径压缩。
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}这个片段与上一份模板是两个独立版本,不要把同名全局变量和函数直接放进同一个文件。用 rankValue 命名,也能避免与标准库中的 std::rank 名称混淆。
四、两种优化可以一起使用
路径压缩优化的是查询经过的路径,按秩合并优化的是合并时的挂接方向,两者并不冲突。将按秩版本的 find 改成路径压缩写法即可,下一题给出组合后的完整程序。
加入路径压缩后,秩不再是实时树高
不压缩时,根的秩可与当前树高对应;压缩会降低实际高度,但不重新计算秩。因此组合优化中的秩是合并用的历史上界,不能解释为当前准确高度,也不是集合元素数量。只比较根的秩,并在等秩合并时递增新根的秩即可。
五、复杂度与适用边界
设有 个元素,初始化为 ;以下区分单次最坏情况与一系列操作的摊还成本:
| 版本 | 查询 / 合并的复杂度说明 |
|---|---|
| 不使用两种优化 | 树可能退化为链,单次最坏 |
| 仅路径压缩 | 单次仍可能为 ;操作序列可用摊还 上界分析,不能直接套用双优化的结论 |
| 仅按秩合并 | 树高为 ,单次查询、合并最坏均为 |
| 路径压缩 + 按秩合并 | 每次操作摊还 , 为增长极慢的反阿克曼函数;不是每次都保证严格 |
按秩合并时,秩为 的根所代表的集合至少有 个元素,因此秩和树高受到对数级上界约束。组合优化后,初始化加 次查询 / 合并的总成本为 ,数组空间为 。复杂度参考:Princeton:仅路径压缩、Cornell:按秩合并与路径压缩。
- 普通并查集适合维护只合并、不拆分的集合;不直接支持删除边后重新判断连通性。
- 它不保存原图中的具体路径,也不能直接给出最短距离。
- 无向图中的连通关系是对称的;有向可达关系通常不是。不能把上一题的有向单源可达性直接换成普通并查集合并来判断。
- 所有操作的节点编号都必须在初始化范围内;本节动态分配
n + 1,不再固定写死101或1005。仅路径压缩版若先形成深链,递归寻根仍可能占用很深的调用栈。
十三、寻找存在的路径
给定节点编号为 1~N 的无向图,判断 source 与 destination 之间是否存在路径:存在输出 1,否则输出 0。题目节点数、边数均在 1~100 之间。
输入先给出节点数、边数,再读入全部无向边,最后给出一对起点、终点。
思路:边对应集合合并,路径存在等价于同属连通块
- 初始化并查集,每个节点各自为一个集合。
- 每读入一条无向边
(s, t),合并s、t所在的集合。 - 全部边处理完后,判断
find(source) == find(destination)。
每条边都连接同一连通块中的两个节点,合并沿路径传递;反过来,只有读到连接两个集合的边时才会合并,所以同根的两个节点之间必然存在无向路径。不需要保存邻接表,也不需要对每次查询重新搜索。
下面是路径压缩 + 按秩合并的完整 ACM 程序;用类封装状态,避免全局变量与多份模板互相影响。
#include <iostream>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
DSU dsu(n);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
dsu.join(s, t);
}
int source, destination;
cin >> source >> destination;
cout << (dsu.isSame(source, destination) ? 1 : 0) << '\n';
return 0;
}#include <iostream>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
DSU dsu(n);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
dsu.join(s, t);
}
int source, destination;
cin >> source >> destination;
cout << (dsu.isSame(source, destination) ? 1 : 0) << '\n';
return 0;
}示例推演:
5 4
1 2
1 3
2 4
3 4
1 45 4
1 2
1 3
2 4
3 4
1 4| 处理的边 | 处理后的集合划分 | 是否真正合并 |
|---|---|---|
| 初始 | {1}、{2}、{3}、{4}、{5} | — |
1—2 | {1,2}、{3}、{4}、{5} | 是 |
1—3 | {1,2,3}、{4}、{5} | 是 |
2—4 | {1,2,3,4}、{5} | 是 |
3—4 | {1,2,3,4}、{5} | 否,已经同属一个集合 |
查询 1 与 4,二者同根,输出 1;若把最后一行改成 1 5,则输出 0。节点 1 与 4 之间没有直接边,但有路径即可,不必直接相邻。
边界情况与方法选择:
- 起点等于终点时,零条边的路径也视为存在,输出
1,不要求该节点与其他节点相连。 - 自环、重复边以及环中的冗余边不会改变集合划分,
join返回false即可,无须重复挂接根或增加秩。 - 无向边只需调用一次
join(s, t),无须再调用join(t, s);并查集中的集合关系本来就是对称的。 - DFS / BFS 也能在 时间内完成这道单次查询题;并查集更便于处理持续加边或同一图上的多次连通性查询,不代表它能替代所有图搜索问题。
- 本程序时间复杂度为 ,其中初始化为 ,处理边和最终查询使用摊还分析;总空间为 ,不存储全部边。
2026-11-15(周日)
图论(十一)
十四、冗余连接
在一棵含 N 个节点、N - 1 条边的无向树中再添加一条边,得到 N 个节点、N 条边的图。删除一条边,使它重新成为树;若有多个答案,返回输入中最后出现的那条边。节点编号为 1~N,题目范围为 1 ≤ N ≤ 1000。
输入先给出 N,再读入 N 条无向边;输出要删除的两个端点,保留该边在输入中的端点顺序。
思路:按输入顺序加入边,用并查集判断是否成环
沿用并查集,从前向后处理每条边 (u, v):
- 两端原本不在同一集合:当前边连接两个连通块,合并它们。
- 两端已经同根:之前接受的边中已经存在
u到v的路径,再加入当前边就会闭合一个环;返回当前边。
join(u, v) 可以同时完成判断和合并:返回 true 表示成功合并,返回 false 表示两端已经连通,不必先 isSame 再重复寻根。
为什么第一次遇到成环边,就是“最后出现”的答案?
树只多加一条边,所以整张图只有一个环,且删掉环上的任意一条边都能恢复成树。环上最后被读到的边出现之前,其余环边还未闭合;读到它时,两端才会通过之前的边连通。因此第一次检测到的成环边,恰好是唯一环中输入位置最靠后的那一条,而不一定是整个输入的最后一条边。
这个提前返回依赖“树 + 一条边”的保证
对任意多环图,第一次成环不代表最后一条可删除边,删除一条边也未必能恢复成树。本题不是要求猜出历史上实际添加的那条边,而是按题目规则选择任意合法删边中的最后一条。
完整代码:路径压缩 + 按秩合并
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
int findRedundantEdge(int n, const vector<pair<int, int>>& edges) {
DSU dsu(n);
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (!dsu.join(edges[i].first, edges[i].second)) {
return i; // 当前边闭合唯一的环。
}
}
return -1; // 合法题目输入一定存在答案。
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
vector<pair<int, int>> edges(n);
for (auto& edge : edges) {
cin >> edge.first >> edge.second;
}
int index = findRedundantEdge(n, edges);
if (index != -1) {
cout << edges[index].first << ' ' << edges[index].second << '\n';
}
return 0;
}#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
int findRedundantEdge(int n, const vector<pair<int, int>>& edges) {
DSU dsu(n);
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (!dsu.join(edges[i].first, edges[i].second)) {
return i; // 当前边闭合唯一的环。
}
}
return -1; // 合法题目输入一定存在答案。
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
vector<pair<int, int>> edges(n);
for (auto& edge : edges) {
cin >> edge.first >> edge.second;
}
int index = findRedundantEdge(n, edges);
if (index != -1) {
cout << edges[index].first << ' ' << edges[index].second << '\n';
}
return 0;
}示例推演:
3
1 2
2 3
1 33
1 2
2 3
1 3| 当前边 | 处理前两端是否连通 | 操作 |
|---|---|---|
1—2 | 否 | 合并 {1}、{2} |
2—3 | 否 | 合并 {1,2}、{3} |
1—3 | 是 | 检测到环,输出 1 3 |
三条边都可以删除,但 1 3 的输入位置最靠后。
- 时间复杂度:,包括初始化与至多
N次合并操作,使用摊还分析。 - 空间复杂度:,本实现保存输入边和并查集数组;也可以像原代码一样边读入边处理,不必保存全部边。
十五、冗余连接 II
在一棵有根有向树上添加一条有向边,得到 N 个节点、N 条边的有向图。删除一条边,使其恢复为有根有向树;若有多个答案,仍返回输入中最后出现的那条边。节点编号为 1~N,题目范围为 1 ≤ N ≤ 1000。
输入先给出 N,再给出 N 条有向边 s → t。有根有向树要求:
- 恰好一个根,根的入度为
0,其余节点的入度均为1。 - 根可以沿有向边到达所有其他节点,总边数为
N - 1。 - 根不一定是节点
1;只有入度条件而没有连通、无环条件,也不足以保证是一棵树。
一、分类:先看是否存在入度为 2 的节点
原树中只有根的入度为 0,其他节点入度为 1。添加一条边只会使它的终点入度增加 1,因此有两种主分支、三种典型情况:
| 情况 | 结构特征 | 应如何删边 |
|---|---|---|
入度为 2,没有有向环 | 一个节点有两个父节点 | 两条入边都可作为候选,优先删除输入较晚的一条 |
入度为 2,同时存在有向环 | 两个父节点问题与环同时出现 | 只能删除该节点两条入边中位于有向环上的那一条 |
不存在入度为 2 的节点 | 新边指向原根,形成有向环 | 删除环上输入位置最靠后的边 |
入度为
2时,不能直接随便删一条入边两条入边只是候选。必须试删后确认能恢复成树;若删掉较晚的一条后仍存在环,就只能删除较早的一条。候选按输入下标倒序保存,可统一满足“多个合法答案取最后出现”的要求。
二、实现步骤
- 读入全部边,统计每个节点的入度,即对边
s → t累加inDegree[t]。 - 从后往前扫描边,收集指向入度为
2的节点的边下标;合法输入下最多只有这样一个节点,且恰好两条候选入边。 - 有候选时,先试删较晚的边:新建并查集,跳过该边,检查其余边能否全部成功合并;能则返回较晚的边,否则返回较早的边。
- 没有候选时,从前往后加入全部边,第一次合并失败的边就是要删除的环边。
为什么这里可以用并查集辅助判断有向树?
并查集本身只判断忽略方向后的连通性与成环情况,不能通用地判断有向环。本题能这样使用,是因为额外结构条件已经排除了歧义:
- 试删入度为
2的节点的一条入边后,剩余边数恰为N - 1,所有节点入度至多为1。 - 如果这些边的无向底图没有环,那么
N个节点、N - 1条无环边必然构成一棵连通的无向树。 - 结合入度至多为
1,便得到唯一的入度为0的根,且所有边沿根向外,形成有根有向树。 - 没有入度为
2的节点时,添加的新边指向原根,所有节点入度均为1;在“原有向树 + 一条边”的保证下,有向环与无向底图中的唯一环对应,可用顺序合并找到最后出现的环边。
不要把“并查集合并失败”等同于“一定存在有向环”
例如
1 → 2、1 → 3、2 → 3是无环有向图,但忽略方向后会形成三角形,并查集照样会检测到环。所以必须先处理入度,再结合本题的树结构保证;下面的试删函数不是任意有向图的通用判树函数。
完整代码:
两份程序各自独立编译。这里沿用同一个并查集类,但重新初始化每次试删所用的状态;辅助函数只返回答案下标,统一由 main 输出。
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
// 仅在本题结构保证、且已选择入度为 2 的节点的一条入边时使用。
bool isTreeAfterRemoveEdge(int n, const vector<pair<int, int>>& edges,
int deleteIndex) {
DSU dsu(n); // 每次试删都必须从全新的并查集开始。
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (i == deleteIndex) {
continue;
}
if (!dsu.join(edges[i].first, edges[i].second)) {
return false; // 剩余边的无向底图存在环。
}
}
return true;
}
// 仅在本题结构保证、且不存在入度为 2 的节点时使用。
int getRemoveEdge(int n, const vector<pair<int, int>>& edges) {
DSU dsu(n);
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (!dsu.join(edges[i].first, edges[i].second)) {
return i;
}
}
return -1;
}
int findRedundantDirectedEdge(int n, const vector<pair<int, int>>& edges) {
vector<int> inDegree(n + 1, 0);
for (const auto& edge : edges) {
++inDegree[edge.second];
}
vector<int> candidates;
for (int i = static_cast<int>(edges.size()) - 1; i >= 0; --i) {
if (inDegree[edges[i].second] == 2) {
candidates.push_back(i); // 较晚的入边先放入。
}
}
if (!candidates.empty()) {
// 合法输入下,恰好有同一节点的两条候选入边。
if (isTreeAfterRemoveEdge(n, edges, candidates[0])) {
return candidates[0];
}
return candidates[1]; // 后一条不可删,则只能删前一条。
}
return getRemoveEdge(n, edges);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
vector<pair<int, int>> edges(n);
for (auto& edge : edges) {
cin >> edge.first >> edge.second;
}
int index = findRedundantDirectedEdge(n, edges);
if (index != -1) {
cout << edges[index].first << ' ' << edges[index].second << '\n';
}
return 0;
}#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
bool isSame(int u, int v) {
return find(u) == find(v);
}
};
// 仅在本题结构保证、且已选择入度为 2 的节点的一条入边时使用。
bool isTreeAfterRemoveEdge(int n, const vector<pair<int, int>>& edges,
int deleteIndex) {
DSU dsu(n); // 每次试删都必须从全新的并查集开始。
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (i == deleteIndex) {
continue;
}
if (!dsu.join(edges[i].first, edges[i].second)) {
return false; // 剩余边的无向底图存在环。
}
}
return true;
}
// 仅在本题结构保证、且不存在入度为 2 的节点时使用。
int getRemoveEdge(int n, const vector<pair<int, int>>& edges) {
DSU dsu(n);
for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
if (!dsu.join(edges[i].first, edges[i].second)) {
return i;
}
}
return -1;
}
int findRedundantDirectedEdge(int n, const vector<pair<int, int>>& edges) {
vector<int> inDegree(n + 1, 0);
for (const auto& edge : edges) {
++inDegree[edge.second];
}
vector<int> candidates;
for (int i = static_cast<int>(edges.size()) - 1; i >= 0; --i) {
if (inDegree[edges[i].second] == 2) {
candidates.push_back(i); // 较晚的入边先放入。
}
}
if (!candidates.empty()) {
// 合法输入下,恰好有同一节点的两条候选入边。
if (isTreeAfterRemoveEdge(n, edges, candidates[0])) {
return candidates[0];
}
return candidates[1]; // 后一条不可删,则只能删前一条。
}
return getRemoveEdge(n, edges);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) {
return 0;
}
vector<pair<int, int>> edges(n);
for (auto& edge : edges) {
cin >> edge.first >> edge.second;
}
int index = findRedundantDirectedEdge(n, edges);
if (index != -1) {
cout << edges[index].first << ' ' << edges[index].second << '\n';
}
return 0;
}三、三个分支的示例
情况 A:两个父节点,但没有有向环
3
1 2
1 3
2 33
1 2
1 3
2 3节点 3 有两条入边。先试删较晚的 2 → 3,剩余 1 → 2、1 → 3 是合法树,因此输出 2 3。删 1 → 3 也可以,但它出现得更早。
情况 B:两个父节点,并且有有向环
4
2 1
3 1
4 2
1 44
2 1
3 1
4 2
1 4节点 1 的入度为 2,两条候选入边按倒序为 3 → 1、2 → 1:
- 先删较晚的
3 → 1,仍有环1 → 4 → 2 → 1,且节点3被隔离,试删失败。 - 只能删
2 → 1,剩余路径为3 → 1 → 4 → 2,以3为根,输出2 1。
这说明“最后出现优先”只适用于合法答案之间的选择,不能为了顺序而删掉不满足条件的边。
情况 C:没有入度为 2 的节点
3
1 2
2 3
3 13
1 2
2 3
3 1所有节点入度均为 1,图中有环 1 → 2 → 3 → 1。顺序合并到 3 → 1 时两端已连通,输出 3 1,它也是环上输入位置最靠后的边。
四、易错点与复杂度
- 记录的是边的输入下标,不是只记录入度为
2的节点编号;删边时必须知道具体跳过哪条入边。 - 每次试删都重新初始化并查集。只“跳过边”并不能撤销以前已经执行过的合并。
- 并查集的
father是集合父指针,不是有向树中真实的父节点;有向入度必须根据原始边单独统计。 - 本题只需一次候选试删;若较晚候选不成立,题目保证存在合法答案,因此较早候选必然成立。若输入不是“有根有向树 + 一条边”,这一推断和候选数量保证都可能失效。
- 不存在入度为
2的节点时,仍然从前往后找第一次成环的边;倒序收集只用于两条入边的优先级,不是让所有分支都倒着合并。 - 时间复杂度:。统计入度和收集候选为 ,其余只做常数次初始化、扫描和并查集合并;不是枚举所有边逐一试删的 。
- 空间复杂度:,包括边数组、入度、并查集和候选下标。
2026-11-16(周一)
图论(十二)
十六、Prim 算法
给定一张无向带权图,选择部分边连接全部顶点,使所选边的权值总和最小。这是最小生成树(Minimum Spanning Tree,MST)问题,可以使用 Prim 或 Kruskal 算法;本节重点学习 Prim。
- 输入:
V E,接着E行u v w,顶点编号为1~V。 - 输出:连接全部顶点所需的最小总权值,不是某一条最短路径的长度。
- 题目范围:
2 ≤ V ≤ 10000、1 ≤ E ≤ 100000、0 ≤ w ≤ 10000。 - 只有图连通时,才存在覆盖全部顶点的生成树。题面没有明确给出不连通时的输出约定;下方模板额外检测不连通,并约定输出
-1,这只是模板的防御性处理。
一、生成树、最小生成树与最短路
一张含 V 个顶点的连通无向图,可以选出 V - 1 条原图中的边,使所有顶点连通且不成环,这样的子图叫生成树。最小生成树是在所有生成树中,边权总和最小的一棵;权值相同时,具体方案可能不唯一。
“有 V 个节点就能用 V - 1 条边连起来”缺少前提
必须保证原图连通,且只能选择原图中已有的边。生成树是覆盖全部顶点的无环连通子图,不是任意“边数较少”的子图,也不是要求任意两点之间都走最短路线。
二、Prim 三部曲与 minDist 的含义
设已经加入生成树的顶点集合为 S。对每个尚未加入的顶点 v:
若没有边把 v 与 S 直接相连,则暂记为 INF。它表示把 v 接到当前树上所需的最小单条边权,不是起点到 v 的累计路径长度。
初始化:所有 minDist 为 INF、isInTree 为 false,任选起点 1,令 minDist[1] = 0。这个 0 只是让根先被选中,不代表实际选择了一条零权边。
每轮执行三步:
- 选点:在树外顶点中,选择
minDist最小的cur。 - 入树:若找不到有限距离的顶点,说明剩余部分与当前树不连通;否则标记
cur入树,并将minDist[cur]累加到答案。 - 更新:遍历
cur的邻居j,若j还在树外且w(cur, j) < minDist[j],则更新minDist[j],同时记录parent[j] = cur。
更新式是:
minDist[j] = min(minDist[j], w(cur, j))minDist[j] = min(minDist[j], w(cur, j))不是 minDist[cur] + w(cur, j);后者是累计路径距离的思路。
为什么这种贪心能得到最小生成树?
S 与树外顶点形成一个切分。所有 minDist 中的最小值,对应跨越这个切分的最轻边。若某棵包含当前已选边的最小生成树没有这条边,加入它会形成环;环上必有另一条跨越该切分的边,其权值不小于新边。用新边替换它,仍得到权值不增加的生成树。因此每次选择都可以保留在某棵最小生成树中。
这也解释了:起点可以任意选;边权相等时可以任选一条最轻边,最终总权值仍最小,但具体树可能不同。
三、邻接矩阵版:总权值与父边一起记录
保留原笔记的矩阵思路,将“只求总权值”和“记录边”合并在同一份代码中。parent 记录每个非根顶点最终通过哪个树内顶点接入,求权值时不必输出它。
#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
struct MSTResult {
bool connected;
long long weight;
vector<int> parent;
};
MSTResult primMatrix(const vector<vector<int>>& grid) {
int n = static_cast<int>(grid.size()) - 1;
const int INF = numeric_limits<int>::max();
vector<int> minDist(n + 1, INF);
vector<bool> isInTree(n + 1, false);
MSTResult result{false, 0, vector<int>(n + 1, -1)};
minDist[1] = 0;
// 每轮接纳一个顶点:共 V 轮,其中根贡献 0,共选择 V - 1 条边。
for (int i = 0; i < n; ++i) {
int cur = -1;
for (int j = 1; j <= n; ++j) {
if (!isInTree[j] &&
(cur == -1 || minDist[j] < minDist[cur])) {
cur = j;
}
}
if (cur == -1 || minDist[cur] == INF) {
return result; // 不连通,不能把 INF 当作真实边权累加。
}
isInTree[cur] = true;
result.weight += minDist[cur];
for (int j = 1; j <= n; ++j) {
if (!isInTree[j] && grid[cur][j] < minDist[j]) {
minDist[j] = grid[cur][j];
result.parent[j] = cur; // 跟随更便宜的接入边一起更新。
}
}
}
result.connected = true;
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
const int INF = numeric_limits<int>::max();
vector<vector<int>> grid(v + 1, vector<int>(v + 1, INF));
for (int i = 0; i < e; ++i) {
int u, to, w;
cin >> u >> to >> w;
// 无向图双向建边;若有重边,保留最小权值,而不是直接覆盖。
grid[u][to] = min(grid[u][to], w);
grid[to][u] = min(grid[to][u], w);
}
MSTResult result = primMatrix(grid);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
struct MSTResult {
bool connected;
long long weight;
vector<int> parent;
};
MSTResult primMatrix(const vector<vector<int>>& grid) {
int n = static_cast<int>(grid.size()) - 1;
const int INF = numeric_limits<int>::max();
vector<int> minDist(n + 1, INF);
vector<bool> isInTree(n + 1, false);
MSTResult result{false, 0, vector<int>(n + 1, -1)};
minDist[1] = 0;
// 每轮接纳一个顶点:共 V 轮,其中根贡献 0,共选择 V - 1 条边。
for (int i = 0; i < n; ++i) {
int cur = -1;
for (int j = 1; j <= n; ++j) {
if (!isInTree[j] &&
(cur == -1 || minDist[j] < minDist[cur])) {
cur = j;
}
}
if (cur == -1 || minDist[cur] == INF) {
return result; // 不连通,不能把 INF 当作真实边权累加。
}
isInTree[cur] = true;
result.weight += minDist[cur];
for (int j = 1; j <= n; ++j) {
if (!isInTree[j] && grid[cur][j] < minDist[j]) {
minDist[j] = grid[cur][j];
result.parent[j] = cur; // 跟随更便宜的接入边一起更新。
}
}
}
result.connected = true;
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
const int INF = numeric_limits<int>::max();
vector<vector<int>> grid(v + 1, vector<int>(v + 1, INF));
for (int i = 0; i < e; ++i) {
int u, to, w;
cin >> u >> to >> w;
// 无向图双向建边;若有重边,保留最小权值,而不是直接覆盖。
grid[u][to] = min(grid[u][to], w);
grid[to][u] = min(grid[to][u], w);
}
MSTResult result = primMatrix(grid);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}与原来 V - 1 轮写法的关系
原代码将全部距离初始化为 10001,利用首次扫描选择节点 1,循环 V - 1 次,最后累加节点 2~V 的 minDist。在图连通、权值均小于哨兵、首次固定选择 1的前提下,最后一个顶点虽未标记入树,它的接入边已经确定,因此仍能得到正确答案。
这里改为显式设置根的距离为 0、执行 V 次选点并当场累加,便于统一理解“接纳 V 个顶点、选择 V - 1 条边”,同时检查是否真的连接了全部顶点。不能只改循环次数却仍把根的 INF 累加进去。
四、如何打印最小生成树的边
- 记录结构:
parent[v]表示最小生成树中v的父顶点;根的父顶点保留为-1。 - 记录时机:每当一条更轻的边改善
minDist[v]时,同步覆盖parent[v];不能只记录第一次发现v的来源。 - 输出时机:算法结束并确认连通之后,跳过根,输出所有
(parent[v], v),恰好V - 1条边。
若只做“打印边”的扩展练习,可以在上面 main 的成功分支中,将 cout << result.weight << '\n'; 替换为:
for (int node = 1; node <= v; ++node) {
if (result.parent[node] != -1) {
cout << result.parent[node] << " -> " << node << '\n';
}
}for (int node = 1; node <= v; ++node) {
if (result.parent[node] != -1) {
cout << result.parent[node] << " -> " << node << '\n';
}
}这里的箭头只是以根 1 为起点描述树的父子关系,原图仍是无向图;这也不是并查集的集合父指针。
题目只要求总权值
提交原题时不要额外打印边,也不要输出根的
-1父节点。父边输出按顶点编号排列即可,不一定等于算法的选点顺序;存在多棵最小生成树时,也不要求与示意图完全相同。
五、数据规模与堆优化版
矩阵版的时间复杂度为 ,通常写作 (建图读入另计);空间复杂度为 ,其中算法辅助数组为 。
当前题面上限为 V = 10000,(V + 1)² 个常见的 4 字节 int 单是元素存储就约需 400 MB(约 382 MiB),还不含其他开销。矩阵版适合理解流程及较小规模的稠密图,不能忽视当前题目的内存与运行时间限制。本题边数上限相对 V² 较小,更适合邻接表加最小堆。
堆中保存 (候选接入边权, 顶点)。当距离改善时压入新条目,旧条目不必原地删除;一个顶点首次有效弹出时入树,之后遇到该顶点的条目直接跳过。父边的更新规则与矩阵版完全相同。
#include <functional>
#include <iostream>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
struct MSTResult {
bool connected;
long long weight;
vector<int> parent;
};
MSTResult primHeap(const vector<vector<pair<int, int>>>& graph) {
int n = static_cast<int>(graph.size()) - 1;
const int INF = numeric_limits<int>::max();
vector<int> minDist(n + 1, INF);
vector<bool> isInTree(n + 1, false);
MSTResult result{false, 0, vector<int>(n + 1, -1)};
// 邻接表条目是 (邻居, 权值),堆条目是 (权值, 顶点)。
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>> que;
minDist[1] = 0;
que.push({0, 1});
int count = 0;
while (!que.empty()) {
auto [dist, cur] = que.top();
que.pop();
if (isInTree[cur]) {
continue; // 旧候选不会让同一个顶点重复入树。
}
isInTree[cur] = true;
++count;
result.weight += dist;
for (const auto& [next, w] : graph[cur]) {
if (!isInTree[next] && w < minDist[next]) {
minDist[next] = w;
result.parent[next] = cur;
que.push({w, next});
}
}
}
result.connected = (count == n);
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
vector<vector<pair<int, int>>> graph(v + 1);
for (int i = 0; i < e; ++i) {
int u, to, w;
cin >> u >> to >> w;
graph[u].push_back({to, w});
graph[to].push_back({u, w});
}
MSTResult result = primHeap(graph);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}#include <functional>
#include <iostream>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
struct MSTResult {
bool connected;
long long weight;
vector<int> parent;
};
MSTResult primHeap(const vector<vector<pair<int, int>>>& graph) {
int n = static_cast<int>(graph.size()) - 1;
const int INF = numeric_limits<int>::max();
vector<int> minDist(n + 1, INF);
vector<bool> isInTree(n + 1, false);
MSTResult result{false, 0, vector<int>(n + 1, -1)};
// 邻接表条目是 (邻居, 权值),堆条目是 (权值, 顶点)。
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>> que;
minDist[1] = 0;
que.push({0, 1});
int count = 0;
while (!que.empty()) {
auto [dist, cur] = que.top();
que.pop();
if (isInTree[cur]) {
continue; // 旧候选不会让同一个顶点重复入树。
}
isInTree[cur] = true;
++count;
result.weight += dist;
for (const auto& [next, w] : graph[cur]) {
if (!isInTree[next] && w < minDist[next]) {
minDist[next] = w;
result.parent[next] = cur;
que.push({w, next});
}
}
}
result.connected = (count == n);
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
vector<vector<pair<int, int>>> graph(v + 1);
for (int i = 0; i < e; ++i) {
int u, to, w;
cin >> u >> to >> w;
graph[u].push_back({to, w});
graph[to].push_back({u, w});
}
MSTResult result = primHeap(graph);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}两份完整代码分别编译运行;堆版也可以使用上一节的打印父边片段,不要把两份 main 或 MSTResult 放进同一文件。
堆版最多产生 个候选条目。计入初始化和建图,时间复杂度可写为 ,空间复杂度为 ,包括邻接表、堆与辅助数组。对连通简单图,常简写为 ;这里采用允许重边、会保留旧条目的写法,堆大小不保证只有 。
六、示例与易错点
原题示例:
7 11
1 2 1
1 3 1
1 5 2
2 6 1
2 4 2
2 3 2
3 4 1
4 5 1
5 6 2
5 7 1
6 7 17 11
1 2 1
1 3 1
1 5 2
2 6 1
2 4 2
2 3 2
3 4 1
4 5 1
5 6 2
5 7 1
6 7 1输出:
66可以选择 1—2、1—3、2—6、3—4、4—5、5—7,六条边的权值均为 1,覆盖七个顶点,总权值为 6。图还有其他同权最小生成树。
再用三角形理解 minDist 和 parent 的更新:1—2 权值 10、1—3 权值 1、3—2 权值 2。
| 本轮入树顶点 | 关键变化 | 累计权值 |
|---|---|---|
1 | minDist[2] = 10、parent[2] = 1;minDist[3] = 1、parent[3] = 1 | 0 |
3 | 用边 3—2 将 minDist[2] 改为 2,同时把 parent[2] 改为 3 | 1 |
2 | 以边权 2 接入,不是以路径长度 1 + 2 = 3 接入 | 3 |
最终树边为 1—3、3—2,总权值为 3。如果只保留节点 2 第一次被发现时的父边,就会错误打印 1—2。
- 零权边合法:不能用
0表示“没有边”;使用大于所有合法权值的INF,且不对它做加法。 - 重边取轻边:矩阵建图使用
min;邻接表允许保留多条边,松弛时自然选择更轻的候选。自环不会连接新顶点,会被入树状态判断排除。 - 父边只更新树外顶点:节点入树后,它的接入边已确定,不再修改。
- 权值累加使用 long long:当前题目上限下答案不超过
(V - 1) × 10000,仍可放入常见的 32 位int;这里使用更宽类型,便于复用模板。 - Prim 与最短路不同:Prim 最小化整棵树的边权和,不保证根到每个顶点的树上路径都最短;外观相似不能混用距离定义或更新公式。
- 图不连通时没有全图生成树:本模板返回失败,不会自动计算全部连通分量的最小生成森林。Prim 本身也允许负边权(需调整哨兵与类型以覆盖数据范围),不依赖本题的非负权限制。
2026-11-17(周二)
图论(十三)
十七、Kruskal 算法
继续解决上一节的无向带权图最小生成树问题:选择原图中的边,连接全部 V 个顶点,使边权总和最小。Prim从当前树出发选点;Kruskal 则从整张图的边出发,按边权从小到大尝试合并连通分量。
输入为 V E,接着 E 行 u v w,顶点编号为 1~V;输出最小生成树的总权值。题目范围为 2 ≤ V ≤ 10000、1 ≤ E ≤ 100000、0 ≤ w ≤ 10000。
一、核心流程:边排序 + 并查集判环
最初不选择任何边,每个顶点独自构成一个连通分量,当前结构是一片森林。
- 将所有边按权值从小到大排序。
- 依次检查边
(u, v, w):- 如果
u、v已在同一分量中,已有所选边构成的路径连接它们,再加这条边会成环,跳过。 - 如果两端属于不同分量,接受这条边,将
w加入答案,并合并两个分量。
- 如果
- 每接受一条边,分量数减少
1。接受到V - 1条边时,全部顶点已经连成一棵树,可以提前停止。 - 扫完所有边仍不足
V - 1条,说明原图不连通,不存在覆盖全部顶点的生成树。
这里判断的是已经选中的边形成的连通关系,不是原图里两端是否存在路径。若按原图的可达性判断,连通图中的边都会被错误跳过。
为什么用并查集?
并查集正好支持“判断两个顶点是否同属一个集合”和“合并两个集合”。可以让
join(u, v)同时完成判断与合并:返回true才接受这条边,返回false就跳过,不必先查询再重复寻根。
二、为什么按最轻边贪心是正确的?
当前选中的边始终构成森林。对一条将被接受的边,取它一端所在的当前分量,与其他顶点形成切分。比它更轻的边都已处理过;若其中某条边现在仍跨越这个切分,当初就不会因两端同分量而被拒绝,也不可能被接受后还跨越当前分量。因此当前边是跨越这个切分的一条最轻边。
根据切分性质,这条边可以加入某棵包含已有选择的最小生成树。也可以用换边理解:将它加入这样的最小生成树会形成环,删去环上另一条跨越该切分、权值不小于它的边,仍然是总权值不增加的生成树。
因此,每次选择都保留得到最优解的可能。不是直接取排序后的前 V - 1 条边,因为较轻的边之间也可能成环。
三、完整代码:路径压缩 + 按秩合并
沿用前面并查集的优化方式,按实际顶点数分配数组,不再使用固定的全局容量。用 chosenEdges 保存真正接受的原图边,同时用于检查边数与扩展打印。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int u, v, weight;
};
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
};
struct MSTResult {
bool connected;
long long weight;
vector<Edge> chosenEdges;
};
// 按值接收边表:排序局部副本,不改变调用者的边顺序。
MSTResult kruskal(int n, vector<Edge> edges) {
sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
return a.weight < b.weight;
});
DSU dsu(n);
MSTResult result{false, 0, {}};
result.chosenEdges.reserve(n - 1);
for (const Edge& edge : edges) {
if (!dsu.join(edge.u, edge.v)) {
continue; // 已连通,再加入就会形成环。
}
result.weight += edge.weight;
result.chosenEdges.push_back(edge); // 保存原图边,不是集合根的连线。
if (static_cast<int>(result.chosenEdges.size()) == n - 1) {
break;
}
}
result.connected =
(static_cast<int>(result.chosenEdges.size()) == n - 1);
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
vector<Edge> edges(e);
for (Edge& edge : edges) {
cin >> edge.u >> edge.v >> edge.weight;
}
MSTResult result = kruskal(v, edges);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int u, v, weight;
};
class DSU {
private:
vector<int> father;
vector<int> rankValue;
public:
explicit DSU(int n) : father(n + 1), rankValue(n + 1, 0) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
}
int find(int u) {
if (father[u] != u) {
father[u] = find(father[u]);
}
return father[u];
}
bool join(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) {
return false;
}
if (rankValue[rootU] < rankValue[rootV]) {
father[rootU] = rootV;
} else if (rankValue[rootU] > rankValue[rootV]) {
father[rootV] = rootU;
} else {
father[rootV] = rootU;
++rankValue[rootU];
}
return true;
}
};
struct MSTResult {
bool connected;
long long weight;
vector<Edge> chosenEdges;
};
// 按值接收边表:排序局部副本,不改变调用者的边顺序。
MSTResult kruskal(int n, vector<Edge> edges) {
sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
return a.weight < b.weight;
});
DSU dsu(n);
MSTResult result{false, 0, {}};
result.chosenEdges.reserve(n - 1);
for (const Edge& edge : edges) {
if (!dsu.join(edge.u, edge.v)) {
continue; // 已连通,再加入就会形成环。
}
result.weight += edge.weight;
result.chosenEdges.push_back(edge); // 保存原图边,不是集合根的连线。
if (static_cast<int>(result.chosenEdges.size()) == n - 1) {
break;
}
}
result.connected =
(static_cast<int>(result.chosenEdges.size()) == n - 1);
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int v, e;
if (!(cin >> v >> e)) {
return 0;
}
vector<Edge> edges(e);
for (Edge& edge : edges) {
cin >> edge.u >> edge.v >> edge.weight;
}
MSTResult result = kruskal(v, edges);
if (!result.connected) {
cout << -1 << '\n';
return 0;
}
cout << result.weight << '\n';
return 0;
}不连通时的输出是模板约定
题面没有明确给出不连通时应输出什么。这里沿用上一节的防御性处理:无法得到全图生成树时输出
-1,不能把它当成原题规定。若题目保证连通,则不会进入这个分支。
四、原代码与规范版的区别
- 原来的“排序、比较两端根、接受边并合并”主流程是正确的;
join(x, y)传入已经找到的根,也不会导致逻辑错误,只是函数内部会再次寻根。 - 原代码只做路径压缩;这里补充按秩合并,使复杂度分析与前面的组合优化模板一致。
- 原代码扫描全部边,不记录接受了多少条。在连通图中依旧正确,只是树已经形成后还会继续检查剩余边;这里在选够
V - 1条时停止。 - 不连通图是需要补上的判断:原代码最终累加的是各连通分量的最小生成树总权值,即最小生成森林的权值,不是全图生成树的权值。
long long用于累计总权值。当前题目范围下(V - 1) × 10000仍可放入常见的 32 位int,加宽是为了方便复用,不是说原题必然溢出。
如果希望打印选中的边,可在 main 中确认连通后添加下面的片段;提交原题时不要额外输出:
for (const Edge& edge : result.chosenEdges) {
cout << edge.u << ' ' << edge.v << ' ' << edge.weight << '\n';
}for (const Edge& edge : result.chosenEdges) {
cout << edge.u << ' ' << edge.v << ' ' << edge.weight << '\n';
}并查集的父指针只表示集合关系,不保证对应原图中的真实边;因此不能遍历 father 来还原最小生成树。Kruskal 不必指定根,直接保存每条接受的 Edge 即可。
五、示例:最轻的边也可能要跳过
4 5
1 2 1
2 3 2
1 3 3
3 4 4
1 4 104 5
1 2 1
2 3 2
1 3 3
3 4 4
1 4 10| 当前边 | 两端是否已连通 | 操作 | 累计权值 |
|---|---|---|---|
1—2,权值 1 | 否 | 接受,合并 1、2 | 1 |
2—3,权值 2 | 否 | 接受,合并 {1, 2} 与 {3} | 3 |
1—3,权值 3 | 是 | 跳过,避免形成 1—2—3—1 环 | 3 |
3—4,权值 4 | 否 | 接受,选够三条边,停止 | 7 |
输出 7。不能直接把排序后的前三条边相加,那样节点 4 仍未接入。
原题的七顶点示例与上一节相同,最小总权值为 6;可以对照Prim 的示例,两种算法可能选出不同的边,但最优总权值相同。
六、Prim 与 Kruskal 对照
| 对比项 | Prim | Kruskal |
|---|---|---|
| 贪心对象 | 当前树与树外顶点之间的最轻接入边 | 全图按权值升序排列的边,跳过成环边 |
| 中间结构 | 从一个起点不断扩张的一棵树 | 多个分量组成的森林,不断合并 |
| 核心状态 | minDist、入树标记,可记录 parent | 边表、并查集,可记录 chosenEdges |
| 常见实现 | 矩阵扫描,或邻接表加最小堆 | 边排序加并查集,不必建立邻接表 |
| 不连通时 | 单次从一个起点只覆盖其所在分量 | 扫描全部边后得到最小生成森林 |
| 常见使用场景 | 矩阵版适合稠密图;堆版也适合稀疏图 | 适合以边表给出的图,尤其是稀疏图 |
两者都解决无向图的最小生成树问题,不是单源最短路算法。本题 V 可达一万、E 可达十万,Kruskal 不需要矩阵的平方级空间。
七、复杂度与易错点
- 时间复杂度:并查集初始化 ;边排序 ;最多
E次合并判断,摊还 。合计 ,连通图的常见表述为 ,主要耗时通常在排序。 - 空间复杂度:,包括并查集、边表副本及所选边;最多保存
V - 1条所选边。本实现按值传参会复制边表,若允许改变原边序,可以改为引用以避免这份复制。 - 排序比较器用严格小于
<:不能写<=;不必用权值相减来比较,以免推广到大权值时发生溢出。 - 同权边不必保持输入顺序:任意处理同权边都能得到最优总权值;具体最小生成树可能不同。只有题目额外规定方案优先级时,才需要进一步设计同权规则。
- 零权、负权都可处理:Kruskal 不依赖边权非负;当前题目只给出非负权。重边可以全部保留,自环会因两端同根被跳过,无需当作新分量连接。
- 只在成功合并时累计:不是每处理一条边都加权、加计数;接受边数才是当前森林的边数。
- 边数够多不代表连通:即使
E ≥ V - 1,也可能有孤立点或多个分量,仍要检查实际接受的边数。 - 森林与树分清:若原图有
C个连通分量,扫完边后会接受V - C条边。此时返回结构里的边与权值仍是最小生成森林,但只有C = 1时connected才为true。
2026-11-18(周三)
今天赶论文,算法学习休息一天。
2026-11-20(周五)
图论(十四)
十八、拓扑排序
给定 N 个文件及其依赖关系,文件编号为 0~N - 1。输入边 S T 表示 T 依赖 S,必须先处理 S,再处理 T,因此建有向边 S → T。
输入先给出 N M,再给出 M 条依赖关系;若能完成全部文件,输出一种合法处理顺序,以空格分隔且行末无空格;若有循环依赖,输出 -1。本题接受多种合法顺序,不要求字典序最小。
一、拓扑排序的准确含义
拓扑排序是把有向图的全部顶点排成一个线性序列,并且对每条有向边 u → v,都满足 u 在序列中出现在 v 之前。不是任意把图中的节点排成一行就算拓扑排序。
- 有向无环图(DAG)当且仅当存在拓扑序。
- 有向环意味着“先后依赖”相互矛盾,无法排列全部顶点。
- 图不必连通;多个独立分量、孤立点同样需要出现在最终序列中。
- 拓扑序可能不唯一,因为没有相互先后约束的顶点可以有不同排列。
二、Kahn 算法:不断删除入度为 0 的节点
inDegree[v] 记录节点 v 在当前剩余图中还有多少条入边,即还有多少条前置依赖尚未解除。入度为 0,说明当前没有未完成的前置约束,可以处理该节点。
- 统计所有节点的入度,将全部入度为 0 的节点加入队列。
- 弹出队首节点
cur,加入结果序列。 - 遍历
cur的每条出边cur → next,执行--inDegree[next],表示删除这条依赖边。 - 如果某个
next的入度恰好减到0,就将它入队。 - 重复直到队列为空;最后检查是否输出了全部
N个节点。
不需要真的从邻接表里删除顶点或边,通过入度递减模拟删除即可。开始时的零入度节点只是第一批可处理对象;后续节点解除全部依赖后也会变成零入度节点,并不是只有原图中的“起点”才有资格处理。
必须等到入度归零,不能发现一个前驱已处理就入队
若
0 → 2、1 → 2,则2必须等待0、1都完成。处理完0时,inDegree[2]只是从2变成1,还不能处理2。这与普通 BFS的“首次发现即入队”条件不同。
三、为什么能排序,也能判断有向环?
- 每次只输出当前入度为
0的节点,它的所有前驱都已经处理。因此只要全部顶点都输出,得到的序列必然满足所有依赖。 - 非空 DAG 必然存在入度为
0的节点;否则沿入边不断寻找前驱,有限个节点中必然重复,从而形成有向环。删除一个零入度节点后仍是 DAG,所以可以不断处理完所有节点。 - 若队列已经为空,却还有节点未处理,则剩余图中每个节点都有未解除的入边,必然存在有向环。
判断标准是 order.size() == N,不是“曾经有零入度节点”,也不是“队列最后为空”——成功或失败时队列最终都会为空。
四、完整代码:邻接表 + 队列
顶点编号连续,使用 vector<vector<int>> 存储出边即可,无需哈希表。将算法单独封装,入度在函数中统计并递减,原邻接表保持不变。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
bool topologicalSort(const vector<vector<int>>& graph, vector<int>& order) {
int n = static_cast<int>(graph.size());
vector<int> inDegree(n, 0);
for (const auto& neighbors : graph) {
for (int next : neighbors) {
++inDegree[next];
}
}
queue<int> que;
for (int node = 0; node < n; ++node) {
if (inDegree[node] == 0) {
que.push(node);
}
}
order.clear();
order.reserve(n);
while (!que.empty()) {
int cur = que.front();
que.pop();
order.push_back(cur);
for (int next : graph[cur]) {
--inDegree[next];
if (inDegree[next] == 0) {
que.push(next);
}
}
}
return static_cast<int>(order.size()) == n;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t); // T 依赖 S:只能建 S -> T,不能反向。
}
vector<int> order;
if (!topologicalSort(graph, order)) {
cout << -1 << '\n';
return 0;
}
for (int i = 0; i < n; ++i) {
if (i > 0) {
cout << ' ';
}
cout << order[i];
}
cout << '\n';
return 0;
}#include <iostream>
#include <queue>
#include <vector>
using namespace std;
bool topologicalSort(const vector<vector<int>>& graph, vector<int>& order) {
int n = static_cast<int>(graph.size());
vector<int> inDegree(n, 0);
for (const auto& neighbors : graph) {
for (int next : neighbors) {
++inDegree[next];
}
}
queue<int> que;
for (int node = 0; node < n; ++node) {
if (inDegree[node] == 0) {
que.push(node);
}
}
order.clear();
order.reserve(n);
while (!que.empty()) {
int cur = que.front();
que.pop();
order.push_back(cur);
for (int next : graph[cur]) {
--inDegree[next];
if (inDegree[next] == 0) {
que.push(next);
}
}
}
return static_cast<int>(order.size()) == n;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<int>> graph(n);
for (int i = 0; i < m; ++i) {
int s, t;
cin >> s >> t;
graph[s].push_back(t); // T 依赖 S:只能建 S -> T,不能反向。
}
vector<int> order;
if (!topologicalSort(graph, order)) {
cout << -1 << '\n';
return 0;
}
for (int i = 0; i < n; ++i) {
if (i > 0) {
cout << ' ';
}
cout << order[i];
}
cout << '\n';
return 0;
}与原代码相比,保留“统计入度、零入度入队、删边更新”的主流程,并作以下调整:
- 用连续编号的邻接表替代
unordered_map,避免遍历不存在的键时顺带插入空条目。 - 直接遍历
graph[cur],不再通过vector<int> files = umap[cur]复制整份出边数组。 - 输出时在非首项前加空格,不再单独访问
result[n - 1],也能兼容空图。 - 算法返回
false时,order可能保留已处理的部分序列,但它不是全图拓扑序;主程序只输出-1,不提前打印部分结果。
题面列出 N ≤ 10^5、M ≤ 10^9,并允许 N = 0,但输入描述与边数下界对此并不完全一致。代码以每条边的端点均合法为前提,额外兼容 N = 0, M = 0,此时输出空行。邻接表仍需要 空间,不能因为题面写了十亿条边,就认为普通内存一定能容纳该规模;本实现会存储全部依赖边。
五、示例:依赖解除后才入队
原题输入:
5 4
0 1
0 2
1 3
2 45 4
0 1
0 2
1 3
2 4初始入度为 [0, 1, 1, 1, 1],队列只有 0。按输入顺序存储出边,队列变化如下:
| 本轮处理节点 | 本轮解除的依赖 | 处理后的队列(队首在左) | 已处理序列 |
|---|---|---|---|
0 | 1、2 入度归零 | [1, 2] | [0] |
1 | 3 入度归零 | [2, 3] | [0, 1] |
2 | 4 入度归零 | [3, 4] | [0, 1, 2] |
3 | 无出边 | [4] | [0, 1, 2, 3] |
4 | 无出边 | [] | [0, 1, 2, 3, 4] |
输出 0 1 2 3 4。0 2 4 1 3 也是合法拓扑序,因为所有边的起点仍在终点之前;不要求每次处理编号最小的文件。
有环并不意味着一开始没有零入度节点
4 3
0 1
1 0
1 24 3
0 1
1 0
1 2节点 3 是孤立点,可以先处理;但 0、1 互相依赖,节点 2 也被它们阻塞。最后只处理了一个节点,故输出 -1。
未输出的节点不一定都在环上
上例中
2不在任何环上,只是依赖于环中的节点。因此这个方法能判断是否存在有向环,但不能直接把“所有未处理节点”当成环上的节点集合,也不会自动给出具体环路。
六、易错点与复杂度
- 方向与编号:
S T表示S → T,增加的是inDegree[T];本题编号从0开始,不能沿用前面从1开始的循环。 - 零出度不是零入度:零入度表示当前没有前置约束;零出度只表示没有后继,不能据此优先输出。
- 初始化必须扫描全部节点:不能只从一个起点搜索,也不能漏掉没有任何边的孤立点。
- 每条依赖只解除一次:图结构不变,每个被处理节点的出边遍历一次。若保留重边,入度统计和递减也必须按重数对应;不能只对一边去重。
- 通常不需要 visited:入度从正数降到
0的时刻最多发生一次;初始零入度节点也只入队一次。正确的入度维护自然避免重复处理。 - 自环与双向依赖:自环
u → u、两点互相依赖都属于有向环,不能成功排序。无向底图有环不等于有向图有环,不能改用普通并查集来判断;例如0 → 1、0 → 2、1 → 2仍是 DAG。 - FIFO 不保证字典序最小:即使初始按编号入队,后续新解锁的小编号也可能排在队尾。若题目额外要求字典序最小,应改用最小堆,且将
front()改为top()、添加<functional>;时间复杂度变为 。本题不需要这个额外条件。 - 时间复杂度:。统计入度扫描所有边,每个节点至多入队、出队一次,处理时每条边至多再扫描一次。
- 空间复杂度:,包括邻接表;不计图的存储,入度、队列与结果数组共 辅助空间。
2026-11-21(周六)
- 今日前往成都,在高铁上撰写本篇笔记;预计明天没有时间学习。
图论(十五)
十九、Dijkstra(朴素版)
给定一张有向带权图,车站编号为 1~N,求从起点 1 到终点 N 的最小总耗时。每行 S E V 表示单向边 S → E,耗时为 V;不能默认双向通行。无法到达终点时输出 -1。
题目范围为 1 ≤ N ≤ 500、1 ≤ M ≤ 5000。当前页面没有明确列出边权数值上限;以下代码使用 long long 保存权值与距离,以边权非负为适用前提,不自行假定一个未给出的权值上限。
一、Dijkstra 解决什么问题?
Dijkstra 是非负边权图上的单源最短路算法:一次运行可以求出源点到所有可达顶点的最短距离。本题只输出其中的 minDist[N]。有向图可以使用;无向图则将每条边双向存储后使用。
- 允许零权边、环和重边,但标准算法不适用于负权边。
- 距离是沿路径的边权总和,不是经过的边数。
- 无权或等权图的最少边数问题可用BFS;一般非负权图中,FIFO 队列不能保证按最短累计距离处理。
二、minDist 是“当前已知距离”,定型后才保证最短
minDist[v]:当前已经找到的从源点到v的最小路径长度;开始时,除源点为0外,其余为INF。visited[v]:v的最短距离是否已经定型,不是“曾经被发现过”。- 尚未定型的
minDist[v]可能继续减小;某个顶点第一次被更新或入堆时,还不能立即标记定型。
Dijkstra 三部曲:
- 选点:从未定型的顶点中,选
minDist最小的cur。 - 定型:如果最小值仍为
INF,说明其余顶点都不可达,停止;否则标记visited[cur] = true。 - 松弛:对每条出边
cur → v,尝试用经过cur的路径改善minDist[v]。
更新公式:
为什么选中的距离可以定型?
假设存在到 cur 的更短路径,沿这条路径找到第一个尚未定型的顶点 x。它的前驱已经定型,并已松弛通向 x 的边,所以 minDist[x] 不大于这条路径到 x 的前缀长度。由于剩余边权非负,该前缀不长于整条路径,便应有 minDist[x] < minDist[cur],与选择 cur 为最小候选矛盾。
没有负环,也不代表能用标准 Dijkstra
例如
1 → 2权值2、1 → 3权值5、3 → 2权值-10,图中没有环,但算法会先把节点2的距离定型为2,错过实际最短距离-5。非负条件用于保证“以后绕路不会更短”,不能只排除负环。
三、完整代码:邻接矩阵 + 线性选点
矩阵用 INF 表示无边;若同一方向出现多条边,取最轻的一条。下面两份程序均约定:所有需要表示的有限边权、最短距离都小于 INF;加法前检查范围,避免有符号溢出。若推广到超过 long long 范围的数据,需要更换数值表示,不能把超范围路径与不可达混为一谈。
#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
const long long INF = numeric_limits<long long>::max();
vector<long long> dijkstraMatrix(const vector<vector<long long>>& grid,
int start) {
int n = static_cast<int>(grid.size()) - 1;
vector<long long> minDist(n + 1, INF);
vector<bool> visited(n + 1, false);
minDist[start] = 0;
for (int i = 0; i < n; ++i) {
int cur = -1;
for (int v = 1; v <= n; ++v) {
if (!visited[v] &&
(cur == -1 || minDist[v] < minDist[cur])) {
cur = v;
}
}
if (cur == -1 || minDist[cur] == INF) {
break; // 剩余顶点不可达,不能对 INF 做路径加法。
}
visited[cur] = true;
for (int v = 1; v <= n; ++v) {
long long w = grid[cur][v];
if (visited[v] || w == INF) {
continue;
}
// 非负边权;只表示严格小于 INF 的有限距离。
if (w >= INF - minDist[cur]) {
continue;
}
long long candidate = minDist[cur] + w;
if (candidate < minDist[v]) {
minDist[v] = candidate;
}
}
}
return minDist;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<long long>> grid(n + 1,
vector<long long>(n + 1, INF));
for (int i = 0; i < m; ++i) {
int from, to;
long long weight;
cin >> from >> to >> weight;
grid[from][to] = min(grid[from][to], weight);
}
vector<long long> minDist = dijkstraMatrix(grid, 1);
cout << (minDist[n] == INF ? -1LL : minDist[n]) << '\n';
return 0;
}#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
const long long INF = numeric_limits<long long>::max();
vector<long long> dijkstraMatrix(const vector<vector<long long>>& grid,
int start) {
int n = static_cast<int>(grid.size()) - 1;
vector<long long> minDist(n + 1, INF);
vector<bool> visited(n + 1, false);
minDist[start] = 0;
for (int i = 0; i < n; ++i) {
int cur = -1;
for (int v = 1; v <= n; ++v) {
if (!visited[v] &&
(cur == -1 || minDist[v] < minDist[cur])) {
cur = v;
}
}
if (cur == -1 || minDist[cur] == INF) {
break; // 剩余顶点不可达,不能对 INF 做路径加法。
}
visited[cur] = true;
for (int v = 1; v <= n; ++v) {
long long w = grid[cur][v];
if (visited[v] || w == INF) {
continue;
}
// 非负边权;只表示严格小于 INF 的有限距离。
if (w >= INF - minDist[cur]) {
continue;
}
long long candidate = minDist[cur] + w;
if (candidate < minDist[v]) {
minDist[v] = candidate;
}
}
}
return minDist;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<long long>> grid(n + 1,
vector<long long>(n + 1, INF));
for (int i = 0; i < m; ++i) {
int from, to;
long long weight;
cin >> from >> to >> weight;
grid[from][to] = min(grid[from][to], weight);
}
vector<long long> minDist = dijkstraMatrix(grid, 1);
cout << (minDist[n] == INF ? -1LL : minDist[n]) << '\n';
return 0;
}与原矩阵代码相比:
- 原来直接
grid[from][to] = weight,会用后读到的重边覆盖较轻边;改为min,避免答案受输入顺序影响。 - 原来的
cur = 1在找不到有限候选时会继续处理已经访问的节点1,没有明确表达“剩余不可达”。改为cur = -1,并在无法选出有限距离时停止,而不是声称原代码一定因此越界。 - 距离由
int改为long long,并增加加法范围检查;不能让大权值相加溢出后被误认为一条更短路径。 - 函数返回全部距离;不可达顶点仍为
INF,主程序只查询终点并按题意输出-1。
二十、Dijkstra(堆优化版)
题目与上一节相同,三部曲及松弛公式也相同。优化的是如何选出距离最小的未定型顶点:不再每轮扫描所有顶点,改用邻接表与最小堆。
一、堆里放的是候选距离,不是原始边权
堆条目保存 (从源点出发的候选累计距离, 顶点)。每次成功松弛一个顶点,就把它的新距离压入堆;堆顶给出当前最小候选。
这不是 Kruskal 那样“把所有原始边按权值排序”,也不是把最轻的一条出边直接当作最短路。某条边本身很轻,不代表走到它的起点所付出的代价也很小。
原代码使用 (节点, 距离) 并自定义比较器,按 .second 排序,这个写法本身正确。这里统一改为 (距离, 节点) 配合 greater<pair<long long, int>>,先比较距离,距离相同再按编号打破平局;不能只交换 pair 的含义而不修改比较方式。
二、同一个顶点可以多次入堆,但只定型一次
priority_queue 不直接修改已有条目的优先级。若某节点的距离从 10 改善为 3,就压入新条目 (3, 节点),旧条目 (10, 节点) 暂时保留。
- 新条目距离更小,会先被弹出;第一次有效弹出时,将这个节点定型。
- 后面再弹出同一节点的旧条目,用
visited[cur]跳过。 - 不能在入堆时标记 visited,否则后续的更短候选可能被挡住。
#include <functional>
#include <iostream>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
const long long INF = numeric_limits<long long>::max();
struct Edge {
int to;
long long weight;
};
vector<long long> dijkstraHeap(const vector<vector<Edge>>& graph, int start) {
int n = static_cast<int>(graph.size()) - 1;
vector<long long> minDist(n + 1, INF);
vector<bool> visited(n + 1, false);
priority_queue<pair<long long, int>, vector<pair<long long, int>>,
greater<pair<long long, int>>> pq;
minDist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
auto [dist, cur] = pq.top();
pq.pop();
if (visited[cur]) {
continue; // 已定型节点的旧候选无需再次扩展。
}
visited[cur] = true;
for (const Edge& edge : graph[cur]) {
if (visited[edge.to]) {
continue;
}
if (edge.weight >= INF - dist) {
continue; // 防止加法溢出,也不把 INF 当有限距离。
}
long long candidate = dist + edge.weight;
if (candidate < minDist[edge.to]) {
minDist[edge.to] = candidate;
pq.push({candidate, edge.to});
}
}
}
return minDist;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<Edge>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int from, to;
long long weight;
cin >> from >> to >> weight;
graph[from].push_back({to, weight}); // 有向图,只添加这一方向。
}
vector<long long> minDist = dijkstraHeap(graph, 1);
cout << (minDist[n] == INF ? -1LL : minDist[n]) << '\n';
return 0;
}#include <functional>
#include <iostream>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
const long long INF = numeric_limits<long long>::max();
struct Edge {
int to;
long long weight;
};
vector<long long> dijkstraHeap(const vector<vector<Edge>>& graph, int start) {
int n = static_cast<int>(graph.size()) - 1;
vector<long long> minDist(n + 1, INF);
vector<bool> visited(n + 1, false);
priority_queue<pair<long long, int>, vector<pair<long long, int>>,
greater<pair<long long, int>>> pq;
minDist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
auto [dist, cur] = pq.top();
pq.pop();
if (visited[cur]) {
continue; // 已定型节点的旧候选无需再次扩展。
}
visited[cur] = true;
for (const Edge& edge : graph[cur]) {
if (visited[edge.to]) {
continue;
}
if (edge.weight >= INF - dist) {
continue; // 防止加法溢出,也不把 INF 当有限距离。
}
long long candidate = dist + edge.weight;
if (candidate < minDist[edge.to]) {
minDist[edge.to] = candidate;
pq.push({candidate, edge.to});
}
}
}
return minDist;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) {
return 0;
}
vector<vector<Edge>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int from, to;
long long weight;
cin >> from >> to >> weight;
graph[from].push_back({to, weight}); // 有向图,只添加这一方向。
}
vector<long long> minDist = dijkstraHeap(graph, 1);
cout << (minDist[n] == INF ? -1LL : minDist[n]) << '\n';
return 0;
}两份完整代码分别编译运行。邻接表将原来的 list<Edge> 改为 vector<Edge>,保留所有重边,遍历时使用 const Edge& 避免不必要的复制;这不会改变算法逻辑。
三、用同一张图对比“接入边”与“累计距离”
有向边:1 → 2 权值 10、1 → 3 权值 1、3 → 2 权值 2。
| 弹出的堆条目(距离,节点) | 操作 | 距离变化 |
|---|---|---|
(0, 1) | 定型 1,松弛两条出边 | minDist[2] = 10,minDist[3] = 1 |
(1, 3) | 定型 3,通过 3 → 2 改善距离 | minDist[2] = 1 + 2 = 3,压入 (3, 2) |
(3, 2) | 定型 2 | 到 2 的最短距离为 3 |
(10, 2) | 2 已定型,跳过旧候选 | 不重复处理 |
如果把这些边视作无向边来运行Prim,节点 2 的接入边权是 2;Dijkstra 中记录的则是源点到 2 的累计距离 3。
| 对比项 | Dijkstra | Prim |
|---|---|---|
| 目标 | 从一个源点到各点的最短距离 | 连接全部顶点的最小生成树总权值 |
| 距离含义 | 源点到该顶点的累计路径长度 | 树外顶点到当前树的最轻接入边权 |
| 更新候选 | minDist[cur] + w(cur, v) | w(cur, v) |
| 常用图与边权条件 | 有向或无向图,边权非负 | 无向图,可含负权;全图生成树要求连通 |
两者程序结构相似,但不能混用 minDist 的定义或松弛公式。若要记录最短路径,可在成功松弛时保存前驱;所得最短路径树也不等于最小生成树。
四、原题示例与复杂度
7 9
1 2 1
1 3 4
2 3 2
2 4 5
3 4 2
4 5 3
2 6 4
5 7 4
6 7 97 9
1 2 1
1 3 4
2 3 2
2 4 5
3 4 2
4 5 3
2 6 4
5 7 4
6 7 9输出 12,一条最短路线为 1 → 2 → 3 → 4 → 5 → 7,总耗时 1 + 2 + 2 + 3 + 4 = 12。
| 实现 | 时间复杂度(计入建图与初始化) | 空间复杂度(含图存储) |
|---|---|---|
| 邻接矩阵 + 线性选点 | ||
| 邻接表 + 最小堆,本节保留旧条目的写法 |
堆版最多产生 M + 1 次入堆,堆大小不保证只有 N。对简单图,由 M ≤ N²,常将复杂度概括为 ;若讨论允许重边的实现,保留 log(M + 1) 更直接。两种实现不计图存储时,矩阵版辅助空间为 ;堆版还需容纳旧候选,辅助空间可达 。
- 稀疏图通常更适合堆版,因为只遍历实际存在的出边;稠密图可以考虑矩阵版,堆不一定更快。不能只因为“节点很多”就认为平方级扫描没有问题。
- 不可达不是距离为 0:源点到自身为
0;其他不可达节点保留INF,最终按题意输出-1。 - 零权边不能当作无边:矩阵必须用独立哨兵表示无边。严格改善时才压堆,零权环不会造成无限入堆。
- 提前结束要看时机:本节为返回全部距离而完整运行;若只求一个终点,可以在它被选中并定型时停止,不能第一次发现终点或将终点入堆就停止。
- 两种 visited 的含义要区分:普通 BFS 常在入队时标记已发现;Dijkstra 的这里表示距离已定型,需在最小候选出堆时标记。
- 边数与权值范围都要核对:
long long不是无限大;本模板的有限距离约定仍须与具体题目的上界相符,超出表示范围不能误报为“无路可达”。

