当前位置:网站首页>【剑指Offer】47. 礼物的最大价值
【剑指Offer】47. 礼物的最大价值
2022-06-27 20:46:00 【LuZhouShiLi】
剑指 Offer 47. 礼物的最大价值
题目
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
思路
- 状态定义:设动态规划矩阵dp,dp(i,j)代表从棋盘的左上角开始,到达单元格(i,j)时能拿到礼物的最大累计价值。
- 转移方程:
- 当i = 0且j = 0时,为起始元素
- 当i = 0且j != 0时,矩阵的第一行元素,只可以从左边到达
- 当i != 0且j = 0时,矩阵的第一列元素,只可以从上边到达
- 当i != 0且j != 0时,可以从左边或者上边到达

代码
class Solution {
public int maxValue(int[][] grid) {
int m = grid.length,n = grid[0].length;// 取出矩阵的行数或者列数
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(i == 0 && j == 0) continue;
if(i == 0) grid[i][j] = grid[i][j] + grid[i][j - 1];// 从左边到达
else if(j == 0)
{
grid[i][j] = grid[i][j] + grid[i - 1][j];
}
else{
grid[i][j] += Math.max(grid[i][j - 1],grid[i - 1][j]);
}
}
}
return grid[m - 1][n - 1];
}
}
边栏推荐
- The latest cloud development wechat balance charger special effect applet source code
- Discuz taobaoke website template / Dean taobaoke shopping style commercial version template
- 跟着存档教程动手学RNAseq分析(一)
- 2022年第一季度“广州好人”刘磊峰:具有强烈的诚信意识和食品安全意识
- Livox Lidar+海康Camera 基于loam的实时三维重建生成RGB彩色点云
- Spug - 轻量级自动化运维平台
- [electron] 基础学习
- 向量召回和字面召回的选择与权衡
- Passerelle de service pour les microservices
- 官宣!Apache Doris 从 Apache 孵化器毕业,正式成为 Apache 顶级项目!
猜你喜欢

Service gateway of microservices

Detect objects and transfer images through mqtt

广告太「野」,吉野家「渡劫」

实践torch.fx:基于Pytorch的模型优化量化神器

月薪3万的狗德培训,是不是一门好生意?

如何设置企业微信群机器人定时发消息?

Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety

SQL Server 2016详细安装教程(附注册码和资源)

netERR_ CONNECTION_ Refused solution

Ice cream or snow "high"?
随机推荐
跟着存档教程动手学RNAseq分析(四):使用DESeq2进行DE分析的QC方法
Azure Kinect DK 实现三维重建 (jetson实时版)
OData - API using SAP API hub in SAP S4 op
个人TREE ALV 模版-加快你的开发
Spark BUG实践(包含的BUG:ClassCastException;ConnectException;NoClassDefFoundError;RuntimeExceptio等。。。。)
月薪3万的狗德培训,是不是一门好生意?
资深猎头团队管理者:面试3000顾问,总结组织出8大共性(茅生)
SQL Server 2016详细安装教程(附注册码和资源)
官宣!Apache Doris 从 Apache 孵化器毕业,正式成为 Apache 顶级项目!
Livox lidar+ Hikvision camera real-time 3D reconstruction based on loam to generate RGB color point cloud
The choice and trade-off between vector recall and literal recall
量化交易入门教程
「R」使用ggpolar绘制生存关联网络图
Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)
netERR_ CONNECTION_ Refused solution
Open source of local run / development library of hiplot online drawing tool
Discuz淘宝客网站模板/迪恩淘宝客购物风格商业版模板
Spug - 轻量级自动化运维平台
Hiplot 在线绘图工具的本地运行/开发库开源
[suggested collection] ABAP essays-excel-4-batch import recommended