Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最小路径和-64 #34

Open
sl1673495 opened this issue May 17, 2020 · 0 comments
Open

最小路径和-64 #34

sl1673495 opened this issue May 17, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

sl1673495 commented May 17, 2020

64.最小路径和

给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

示例:

输入:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

https://leetcode-cn.com/problems/minimum-path-sum

思路

找状态转移方程

首先这题要想清楚的一点是,到达了一个格子只有两种可能:

  1. 从左边来。
  2. 从上边来。

有了这个思路,状态转移方程其实就可以定义出来了:dp[i] = min(dp[left], dp[top])

找基础状态

其实第一行和第一列都是基础状态,第一行的格子只有可能从左边过来,而第一列的格子只可能从上面过来。

开始动手

/**
 * @param {number[][]} grid
 * @return {number}
 */
let minPathSum = function (grid) {
    let y = grid.length
    if (!y) {
        return 0
    }
    let x = grid[0].length

    let dp = []
    for (let i = 0; i < y; i++) {
        dp[i] = []
    }

    dp[0][0] = grid[0][0]
    
    // 第一行的基础状态 记得加上左边格子的值
    for (let j = 1; j < x; j++) {
        dp[0][j] = grid[0][j] + dp[0][j - 1]
    }

    // 第一列的基础状态 加上上方格子的最优解即可
    for (let i = 1; i < y; i++) {
        dp[i][0] = grid[i][0] + dp[i - 1][0]
    }

    // 开始求左上往右下求解
    for (let i = 1; i < grid.length; i++) {
        for (let j = 1; j < grid[i].length; j++) {
            let cur = grid[i][j]
            let fromUp = cur + (dp[i - 1][j] !== undefined ? dp[i - 1][j]: Infinity)
            let fromLeft = cur + (dp[i][j - 1] !== undefined ? dp[i][j - 1]: Infinity)

            dp[i][j] = Math.min(
                fromUp,
                fromLeft
            )
        }
    }
    return dp[y - 1][x - 1]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant