数字三角形最大路径和

news/2025/3/16 16:43:54/文章来源:https://www.cnblogs.com/YP-L/p/18775218
  1 #include <iostream>
  2 #include <vector>
  3 #include <algorithm>
  4 using namespace std;
  5 
  6 // 自顶向下的方式
  7 pair<int, vector<int>> maximumTotal(vector<vector<int>>& triangle) {
  8     int n = triangle.size();
  9     if (n == 0) return {0, {}};
 10 
 11     /*    dp[i][j] 表示从第 i 行第 j 列到底部的最大路径和
 12         要明白dp这个变量的数据格式是什么样的,它是一个类似这样的格式:
 13             就是一个二维数组,n*n的二维数组,矩阵一样
 14     */
 15     vector<vector<int>> dp(n, vector<int>(n, 0));    
 16 
 17     // parent[i][j] 记录 (i, j) 位置的前驱节点 (i-1, k)
 18     vector<vector<int>> parent(n, vector<int>(n, -1));
 19 
 20     // 初始化第一行
 21     dp[0][0] = triangle[0][0];
 22 
 23     int currenti, currentj;
 24     // 自顶向下计算 dp 数组
 25     for (int i = 1; i < n; ++i) {
 26         for (int j = 0; j <= i; ++j) {
 27             // 处理左边界
 28             if (j == 0) {  
 29                 /* 
 30                     dp[i][j]表示当前这个[i][j]节点对于的前面所有路径的最大和
 31                     ,由于左边界的前驱节点只能有一个,就是[i-1][j]这个节点,即[i-1][0]这个节点
 32                     所以[i][j]节点对于的前面所有路径的最大和dp[i][j]就是前驱节点的最大路径和再
 33                     加上当前这个节点的值triangle[i][j],右边界的节点同理
 34                 
 35                 */
 36                 dp[i][j] = triangle[i][j] + dp[i - 1][j];  
 37             
 38                 /*
 39                     在数字三角形问题中,每个位置 (i, j) 的前驱节点只能是 (i-1, j-1) 或 (i-1, j)。
 40                     因此,前驱节点的行索引一定是 i-1,不需要额外存储。所以下面的这行代码只存储了j
 41                 */
 42                 parent[i][j] = j;  // 前驱节点是 (i-1, j)   parent[1][0]=0
 43             }
 44             // 处理右边界
 45             else if (j == i) {
 46                 dp[i][j] = triangle[i][j] + dp[i - 1][j - 1];
 47                 currenti = i - 1;
 48                 currentj = j - 1;
 49                 parent[i][j] = j - 1;  // 前驱节点是 (i-1, j-1)
 50             }
 51             // 中间位置,由于[i][j]面临着两个前驱节点[i-1][j - 1]和[i-1][j],
 52             // 那么此时就需要判断这两个前驱节点的最大路径和哪个大,哪个大就选择用当前[i][j]的节点值
 53             // triangle[i][j]加上这个大的最大路径和
 54             else {
 55                 if (dp[i - 1][j - 1] > dp[i - 1][j]) {
 56                     dp[i][j] = triangle[i][j] + dp[i - 1][j - 1];
 57                     currenti = i - 1;
 58                     currentj = j - 1;
 59                     parent[i][j] = j - 1;  // 前驱节点是 (i-1, j-1)
 60                 } else {
 61                     dp[i][j] = triangle[i][j] + dp[i - 1][j];
 62                     currenti = i - 1;
 63                     currentj = j;
 64                     parent[i][j] = j;  // 前驱节点是 (i-1, j)
 65                 }
 66             }
 67             printf("dp[%d][%d] = triangle[%d][%d] + dp[%d][%d] = %d\n", i, j, i, j, currenti, currentj, dp[i][j]);
 68         }
 69     }
 70 
 71     // 找到最大路径和的终点
 72     int max_sum = *max_element(dp[n - 1].begin(), dp[n - 1].end());
 73     // max_element(dp[n - 1].begin(), dp[n - 1].end())找到dp中最大的路径和的位置对应的迭代器,
 74     // 然后再减去起始位置的迭代器dp[n - 1].begin(),就得到了最大的路径和这个位置相对起点的位移量,也就是索引,
 75     // 这个索引就是最大的路径和当前位置在最后一行的索引位置了。
 76     int end_index = max_element(dp[n - 1].begin(), dp[n - 1].end()) - dp[n - 1].begin();
 77     // printf("end_index = %d\n",end_index);
 78     
 79     // 先把记录每个节点的前驱节点的二维数组parent打印出来
 80     // 遍历二维数组
 81 //    cout<<"\n--------------开始打印前驱节点的二维数组------------"<<endl;
 82 //    for (int i = 0; i < n; i++) {          // 遍历行
 83 //        for (int j = 0; j < n; j++) {      // 遍历列
 84 //            cout << "parent[" << i << "][" << j << "] = " << parent[i][j] << " ";
 85 //        }
 86 //        cout << endl; // 每行结束后换行
 87 //    }
 88 //    cout<<"-----------------------------------------------------\n"<<endl;
 89     // 回溯构建路径
 90     vector<int> path;
 91     int current_row = n - 1, current_col = end_index;
 92     while (current_row >= 0) {
 93         path.push_back(triangle[current_row][current_col]);
 94         if (current_row > 0) {
 95             current_col = parent[current_row][current_col];
 96         }
 97         current_row--;
 98     }
 99     reverse(path.begin(), path.end());  // 反转得到正序
100 
101     return {max_sum, path};
102 }
103 
104 int main() {
105     vector<vector<int>> triangle = {
106           {7},
107         {3, 8},
108        {8, 1, 0},
109       {2, 7, 4, 4},
110      {4, 5, 2, 6, 5}
111     };
112            //  7 3 8 7 5   30
113     auto result = maximumTotal(triangle);
114     cout << "最大路径和为: " << result.first << endl;
115     cout << "最大路径为: ";
116     for (int num : result.second) {
117         cout << num << " ";
118     }
119     return 0;
120 }
数字三角形最大路径和

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/899843.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

查询实战

统计员工性别并返回数据: select if(gender=1,man,women) 性别,count(*) from tb_emp group by gender;统计员工职位并返回数据: selectcase job when 1 then 班主任when 2 then 讲师when 3 then 学工主管when 4 then 教研主管else 未分配 end 职位,count(*) from tb_emp group…

grpc使用postman测试-问题集合

问题1:postman中proto文件import问题 Unresolved "import" directives We could not find some of the files imported by the .proto file. Specify import paths to those unresolved files using the options below.解决方法: 项目结构如下 - code |- pbentity…

Qt利用QScrollArea和QLabel实现滚轮完整显示OpenCV图片大小

解决三个常见问题,满足大部分UI界面需求。1、加载图像尺寸过大(大于窗口尺寸),在窗口自适应缩放显示大小,不改变宽高比例。2、加载图像尺寸小于窗口尺寸,使图像对齐居中显示在窗口。3、加载图像尺寸过大(大于窗口尺寸),不对图像进行缩放显示,而是在窗口产生滚轮来显示…

MYSQL-DQL操作

基本查询:查询特定列: select name,entrydate from tb_emp; 查询所有: select * from tb_emp; 查询并起别名: select name as bbb,entrydate as aaa from tb_emp;(as可省略) 去除重复记录: select distinct job from tb_emp; 条件查询:点击查看代码 select * from tb_emp where…

第二章练习题

2.1 点击查看代码 TempStr = input("请输入带有符号的温度值:") if isinstance(TempStr, str) and TempStr[-1] in [F, f]:C = int((float(TempStr[0:-1]) - 32) / 1.8)print(f"转换后的温度是{C}C") elif isinstance(TempStr, str) and TempStr[-1] in […

DBeaver Ultimate Edtion 25.0 Multilingual (macOS, Linux, Windows) - 通用数据库工具

DBeaver Ultimate Edtion 25.0 Multilingual (macOS, Linux, Windows) - 通用数据库工具DBeaver Ultimate Edtion 25.0 Multilingual (macOS, Linux, Windows) - 通用数据库工具 One tool for all data sources 请访问原文链接:https://sysin.org/blog/dbeaver/ 查看最新版。原…

book_77_78作业

第2章程序练习题 2.1改造温度转换的输入(不会) 2.2汇率转换 2.3重量转换 2.4彩色蟒蛇 2.5等边三角形 2.6叠加等边三角形 2.7六角形 2.8正方形螺旋

[I.2]个人作业:软件案例分析

项目 内容这个作业属于哪个课程 2025春季软件工程(罗杰、任健)这个作业的要求在哪里 [I.2]个人作业:软件案例分析我在这个课程的目标是 在PSP中精进个人代码技术,在TSP中提高团队合作凝聚力这个作业在哪个具体方面帮助我实现目标 分析市场上的软件案例,全面地了解软件工程的…

Tailscale subnet-on-android

前言啊哈,前段时间提了个issue,然后开发者那边回复了 再过了一段事件,合并了。Jan 17合并的,Feb 4发布的,那我倒要看看有没有新东西。不错不错,新功能加上了。 subnet有什么用 有人要问了,你安卓又不是路由器,搞个subnet干啥? 但是安卓可以开热点啊,尤其是在外面的网…

根据索引进行MySQL查询的简单优化

查询优化SQL让SQL尽量可以命中索引,可以提示查询的效率(但是数据库如果不走索引的速度较快,就不会去走索引)最左匹配法则由于联合索引中包括了多个列,那么对于这多个列的匹配就有一定的规则,就是最左匹配法则, 在使用联合索引时,必须满足从左边开始匹配索引列。假设现在…

FastAPI依赖注入:参数共享与逻辑复用

扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长第一章:依赖注入核心原理 1.1 依赖树构建机制 from fastapi import Dependsdef auth_service():return OAuth2Scheme()def db_conn(auth: dict = Depends(auth_service)):return Database(creds=auth)@app.get(&q…

洛谷-P1449 后缀表达式

重操旧业~ 本菜鸡看到题就只会想到数组,但后来发现不可行,出去俩元素,还得进来一个元素,不好调o(╥﹏╥)o emm...但还是有所收获的,2转2,利用2-0,而不是直接强制int转换哦 同时也发现被题中举的例子迷惑了,数字可不一定是个位数! 1、此题采用栈和二叉树的后序遍历思想(…