leetcode-64. 最小路径和-js迭代法

 /**
  * 思路:(动态规划 迭代法)
  *     状态:位置坐标(每走一步,改变的是当下的位置坐标)
  *     选择:每走一步,可以选择向下,也可以选择向右
  *     dp数组定义:
  *         minPathSum(grid, i, j):grid(0, 0) 走到 grid(i, j) 的最小路径和
  *     base case:
  *         dp[0][i] = sum(dp[0][0...i])
  *         dp[j][0] = sum(dp[0...j][0])
  *     状态选择方程:
  *         dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
  */
var minPathSum = function(grid) {
    let rowLen = grid.length;
    let colLen = grid[0].length;

    // 定义dp数组
    let dp = new Array(rowLen);
    for (let i = 0; i < rowLen; i++) {
        dp[i] = new Array(colLen).fill(0)
    }

    // base case
    dp[0][0] = grid[0][0]
    for (let j = 1; j < colLen; j++) {
        dp[0][j] = dp[0][j-1] + grid[0][j];
    }
    for (let k = 1; k < rowLen; k++) {
        dp[k][0] = dp[k-1][0] + grid[k][0];
    }
    
    // 遍历二维数组,向右或向下移动
    for (let i = 1; i < rowLen; i++) {
        for (let j = 1; j < colLen; j++) {
            dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
        }
    }

    return dp[rowLen-1][colLen-1];
};

你可能感兴趣的:(leetcode,#,动态规划,leetcode,javascript,动态规划)