zoukankan      html  css  js  c++  java
  • [LeetCode] 64. Minimum Path Sum(最小路径和)

    Description

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
    给定一个 m x n 的矩阵,矩阵元素都是非负书,寻找一条从左上角到右下角的路径,使得路径上的数的和最小。

    Note

    You can only move either down or right at any point in time.

    Examples

    Example 1

    Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
    Output: 7
    Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
    

    Example 2

    Input: grid = [[1,2,3],[4,5,6]]
    Output: 12
    

    Constraints

    • m == grid.length

    • n == grid[i].length

    • 1 <= m, n <= 200

    • 0 <= grid[i][j] <= 100

    Solution

    动态规划其中一道例题,状态方程如下:

    [ exttt{dp(i, j)} = egin{cases} exttt{dp(i - 1, j)} + exttt{grid[i][j]}, & j = 0 \ exttt{dp(i, j - 1)} + exttt{grid[i][j]}, & i = 0 \ exttt{dp(i - 1, j - 1)} + min( exttt{grid[i - 1][j]}, exttt{grid[i][j - 1]}), & else end{cases} ]

    其中 dp(i, j) 表示到 (i, j) 位置时的最短路径

    import kotlin.math.min
    
    class Solution {
        fun minPathSum(grid: Array<IntArray>): Int {
            val dp = Array(grid.size) { IntArray(grid[0].size) }
            dp[0][0] = grid[0][0]
            for (i in 1..grid.lastIndex) {
                dp[i][0] = dp[i - 1][0] + grid[i][0]
            }
            for (i in 1..grid[0].lastIndex) {
                dp[0][i] = dp[0][i - 1] + grid[0][i]
            }
    
            for (i in 1..grid.lastIndex) {
                for (j in 1..grid[i].lastIndex) {
                    dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
                }
            }
    
            return dp.last().last()
        }
    }
    
  • 相关阅读:
    交换变量方法总结
    Java Object Model(一)
    Git命令文本手册
    移动端浏览器touch事件的研究总结
    jQuery中的end()方法
    AngularJs开发——控制器间的通信
    网站收藏
    HTTP Content-type 对照表
    ViewData和ViewBag的那些事
    jQuery选择器
  • 原文地址:https://www.cnblogs.com/zhongju/p/13943695.html
Copyright © 2011-2022 走看看