golang力扣leetcode 64.最小路径和

简介: golang力扣leetcode 64.最小路径和

64.最小路径和

64.最小路径和

题解

动态规划四要素

  1. 状态 State
    灵感,创造力,存储小规模问题的结果
  2. 方程 Function
    状态之间的联系,怎么通过小的状态,来算大的状态
  3. 初始化 Intialization
    最极限的小状态是什么,起点
  4. 答案 Answer
    最大的那个状态是什么,终点

state: dp[x][y]从起点走到 x,y 的最短路径

function: dp[x][y] = min(dp[x-1][y], dp[x][y-1]) + A[x][y]

intialize: dp[0][0] = A[0][0]

answer: dp[n-1][m-1]

代码

package main
func minPathSum(grid [][]int) int {
  dp := make([][]int, len(grid))
  for i := 0; i < len(grid); i++ {
    dp[i] = make([]int, len(grid[i]))
    copy(dp[i], grid[i])
  }
  for i := 0; i < len(grid); i++ {
    for j := 0; j < len(grid[i]); j++ {
      if i == 0 && j == 0 {
        dp[i][j] = grid[i][j]
      } else if i == 0 {
        dp[i][j] = dp[i][j-1] + grid[i][j]
      } else if j == 0 {
        dp[i][j] = dp[i-1][j] + grid[i][j]
      } else {
        dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
      }
    }
  }
  return dp[len(grid)-1][len(dp[len(grid)-1])-1]
}
func min(a, b int) int {
  if a > b {
    return b
  }
  return a
}



目录
相关文章
|
4月前
【LeetCode 35】112.路径总和
【LeetCode 35】112.路径总和
43 0
|
4月前
【LeetCode 36】113.路径总和II
【LeetCode 36】113.路径总和II
43 0
|
4月前
|
程序员 C语言
【C语言】LeetCode(力扣)上经典题目
【C语言】LeetCode(力扣)上经典题目
|
4月前
【LeetCode 34】257.二叉树的所有路径
【LeetCode 34】257.二叉树的所有路径
40 0
|
4月前
|
索引
力扣(LeetCode)数据结构练习题(3)------链表
力扣(LeetCode)数据结构练习题(3)------链表
125 0
|
4月前
力扣(LeetCode)数据结构练习题(2)
力扣(LeetCode)数据结构练习题(2)
41 0
|
4月前
|
存储
力扣(LeetCode)数据结构练习题
力扣(LeetCode)数据结构练习题
78 0
|
5月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
6月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
78 6
|
6月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
151 2