当前位置:网站首页>【LeetCode】64. 最小路径和 - Go 语言题解
【LeetCode】64. 最小路径和 - Go 语言题解
2022-07-30 22:48:00 【想变厉害的大白菜】
一、题目描述
给定一个包含非负整数的 m * n
网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例 1:
输入:grid = [[1,3,1],[1,5,1],[4,2,1]]
输出:7
解释:因为路径 1→3→1→1→1 的总和最小。
示例 2:
输入:grid = [[1,2,3],[4,5,6]]
输出:12
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
题目链接:https://leetcode.cn/problems/minimum-path-sum
二、解题思路
我们将经过的格子的重量叠加到当前到的格子上,就是当前路径的和。
从左上角到右下角的路径,每走一步只能是向右走或者向下走,因此到达某一个格子只会是 从上面来 的或者 从左边来 的。
因此要找 最小 路径的话,我们在叠加当前格子时,要选择已经走过的代价比较小的那条路:选择上面或者左边格子比较小的那一个。
也有例外:第一横排只能是左边来的,第一竖列只能是上面来的。
我们可以一排一排遍历:
第一排:grid[i][j] = grid[i][j] + grid[i][j-1]
第一列:grid[i][j] = grid[i][j] + grid[i-1][j]
其他位置:
grid[i][j] = grid[i][j] + min(grid[i-1][j],grid[i][j-1])
三、我的题解
Go 语言代码:
func minPathSum(grid [][]int) int {
m := len(grid)
n := len(grid[0])
for i:=0; i<m;i++{
for j:=0; j<n;j++{
if i==0 && j==0{
continue
}else 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] = grid[i][j] + min(grid[i-1][j],grid[i][j-1])
}
}
}
return grid[m-1][n-1]
}
func min(a,b int) int {
if a<=b {
return a
}else{
return b
}
}
评判结果:
边栏推荐
- MySQL连接时出现2003错误
- Go1.18升级功能 - 模糊测试Fuzz 从零开始Go语言
- BFS题单总结
- IJCAI2022 Tutorial | Spoken Language Comprehension: Recent Advances and New Fields
- 成功解决ModuleNotFoundError: No module named ‘Image‘
- OpenCV笔记(二十):滤波函数——filter2D
- "NIO Cup" 2022 Nioke Summer Multi-School Training Camp 4 DHKLN
- mysql获取当前时间
- EasyExcel comprehensive course combat
- 【无标题】
猜你喜欢
cmd (command line) to operate or connect to the mysql database, and to create databases and tables
2021GDCPC广东省大学生程序设计竞赛 H.History
Navicat cannot connect to mysql super detailed processing method
# # yyds dry goods inventory interview will brush TOP101: to determine whether there is a part of the list
详解操作符
matlab标量场作图
通过社交媒体建立个人IP的 5 种行之有效的策略
The most complete Redis basic + advanced project combat summary notes in history
鳄梨价格数据集(Avocado Prices)
MySQL索引常见面试题(2022版)
随机推荐
MySQL进阶sql性能分析
482-静态库、动态库的制作、使用及区别
PyTorch model export to ONNX file example (LeNet-5)
MySql 5.7.38 download and installation tutorial, and realize the operation of MySql in Navicat
[MySQL] Mysql transaction and authority management
Abstract classes and interfaces (study notes)
Compressing Deep Graph Neural Networks via Adversarial Knowledge Distillation
Day016 类和对象
TCP 连接 三次握手 四次挥手
cmd (command line) to operate or connect to the mysql database, and to create databases and tables
【MySQL】DQL相关操作
openim支持十万超级大群
【无标题】
Jetson AGX Orin 平台关于c240000 I2C总线和GMSL ses地址冲突问题
PS基础学习(一)
ThinkPHP高仿蓝奏云网盘系统源码/对接易支付系统程序
解决一个Mysql的utf8编码导致的问题
ML's shap: Based on FIFA 2018 Statistics (2018 Russia World Cup) team match star classification prediction data set using RF random forest + calculating SHAP value single-sample force map/dependency c
ZZULIOJ:1120: 最值交换
通过对抗性知识蒸馏压缩深度图神经网络