当前位置:网站首页>【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
}
}
评判结果:

边栏推荐
猜你喜欢

Computer shortcut icon whitening solution

Navicat connection MySQL error: 1045 - Access denied for user 'root'@'localhost' (using password YES)

cmd (command line) to operate or connect to the mysql database, and to create databases and tables

Go语学习笔记 - gorm使用 - 事务操作 Web框架Gin(十一)

MySql 5.7.38 download and installation tutorial, and realize the operation of MySql in Navicat

vulnhub靶机AI-Web-1.0渗透笔记

A detailed explanation: SRv6 Policy model, calculation and drainage

2sk2225代换3A/1500V中文资料【PDF数据手册】

Ningbo Zhongning Pawn will transfer 29.5% of the equity for 2.8338 million yuan, and the owner's equity in 2021 will be 9.6875 million yuan

Gxlcms有声小说系统/小说听书系统源码
随机推荐
【翻译】作为混沌网的LFX门徒的经验
Go的Gin框架学习
# Dasctf 7月赋能赛 WP
Day016 类和对象
openim支持十万超级大群
正则表达式语法及使用
【无标题】
打动中产精英群体,全新红旗H5用产品力跑赢需求
A detailed explanation: SRv6 Policy model, calculation and drainage
WSL安装图形界面并通过xrdp/X-Launch访问
IJCAI2022教程 | 口语语言理解:最新进展和新领域
Excel basic study notes
matlab标量场作图
电脑快捷方式图标变白解决方案
第十九周进度(了解物联网基础知识)
2022.7.27
When Navicat connects to MySQL, it pops up: 1045: Access denied for user 'root'@'localhost'
1064 Complete Binary Search Tree
EasyExcel comprehensive course combat
通过社交媒体建立个人IP的 5 种行之有效的策略