当前位置:网站首页>力扣64-最小路径和——动态规划入门题型
力扣64-最小路径和——动态规划入门题型
2022-07-17 17:15:00 【张怼怼√】
题目描述
给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
解题思路
- 状态定义:grid [ i ][ j ] 被定义为点( i , j )处的最小路径;
- 状态转移方程:此时一般要分四类情况讨论
当左边和上边都是矩阵边界时: 即当 i = 0, j = 0时,其实就是起点, grid [ i ] [ j ] = grid [ i ] [ j ];
当左边和上边都不是矩阵边界时: 即当 i 和 j 都不为 0 , grid [ i ] [ j ] = min( grid [ i -1 ] [ j ] , grid [ i ] [ j - 1] ) + grid [ i ] [ j ];
当只有左边是矩阵边界时: 只能从上面来,即当 i = 0, j 不等于 0 时, grid [ i ] [ j ] = grid [ i ] [ j - 1] + grid [ i ] [ j ];
当只有上边是矩阵边界时: 只能从左面来,即当 i 不为 0 , j = 0 时, grid [ i ] [ j ] = grid [ i - 1] [ j ] + grid [ i ] [ j ];
- 最终返回值返回矩阵右下角的状态即可:return grid[m-1][n-1];
输入输出示例

代码
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && j ==0) grid[i][j] = grid[i][j];
else if(i == 0){
grid[i][j] = grid[i][j-1] + grid[i][j];
}else if(j == 0){
grid[i][j] = grid[i-1][j] + grid[i][j];
}else {
grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
}
}
}
return grid[m-1][n-1];
}
}边栏推荐
- 最小交换次数
- 脉冲函数、阶跃函数和斜坡函数及脉冲响应
- go web
- 关于TCP/IP协议漏洞的安全措施
- Go unit test
- MOF customized material | NH (2) -uio66/rgo Graphene Oxide Nanocomposite | methylene blue loaded zif-90 nanoparticles
- Stable super odds, 9 years old mixin | 2022 Jincang innovative product launch was successfully held
- [C language programming 7] BTB model
- 懒到骨子里了,我在CSDN写文章都懒得自己写了,基于selenium模拟写文章
- Can you view MySQL data table structure in two ways?
猜你喜欢

基于STM32设计的云端健康管理系统(采用阿里云物联网平台)

Is the career direction of test / development programmers over 35 a turning point in the workplace?

10分钟自定义搭建行人分析系统,检测跟踪、行为识别、人体属性All-in-One!

松下A6伺服驱动器外部绝对值光栅尺全闭环参数设置

Azkaban 安装文档

动态内存规划

通货收缩的市场何时反转?我们该如何操作?2020-03-13
[email protected] @Zif67 nanomaterial"/>Nitrogen heterocyclic molecule modified uio-66-nh2 | polyethyleneimine modified uio-66-nh2| [email protected] @Zif67 nanomaterial

When will the moon appear

Cloud health management system based on STM32 (using Alibaba cloud Internet of things platform)
随机推荐
Competition notes: numpy learning notes
Logical operator 1 (Gretel software - Jiuye training)
How can MySQL delete data tables and associated data tables
逻辑运算符1(阁瑞钛伦特软件-九耶实训)
Cobalt iron bimetallic organic skeleton cox/mil-100 (FE) | [email protected]
Useeffect summary
Yunxi focuses on store broadcast solutions to accelerate global layout
收益风险比:投资机会最重要指标 2020-03-14
Summary of ultrasonic sensor series articles
虞美人·寄公度
深度梳理:机器学习建模调参方法总结
Yu Meimei, Ji Gongdu
R language -- principle of Cox model calibration curve (I) data source
Azkaban installation documentation
XML建模(简单易学)
关于TCP/IP协议漏洞的安全措施
市场“不确定性”中的投资逻辑 2020-03-18
Minimum exchange times
全球金融危机来袭,如何科学理性投资?2020-03-17
About the "bottom reading" mentality, it makes you exhausted 2020-03-15