zoukankan      html  css  js  c++  java
  • 64. Minimum Path Sum(js)

    64. Minimum Path Sum

    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.

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

    Example:

    Input:
    [
      [1,3,1],
      [1,5,1],
      [4,2,1]
    ]
    Output: 7
    Explanation: Because the path 1→3→1→1→1 minimizes the sum.
    题意:给一个二维数组,从左上至右下,求出经过项的和最小
    代码如下:
    /**
     * @param {number[][]} grid
     * @return {number}
     */
    //让每项和它的左边和上边比较
    var minPathSum = function(grid) {
        var rowLen=grid.length;
        var colLen=grid[0].length;
        var res=[];
        for(var i=0;i<rowLen;i++){
            res[i]=new Array();
            for(var j=0;j<colLen;j++){
                res[i][j]=0;
            }
        }
        res[0][0]=grid[0][0];
        //第一行
        for(var i=1;i<colLen;i++){
            res[0][i]=res[0][i-1]+grid[0][i];
        }
        //第一列
        for(var i=1;i<rowLen;i++){
            res[i][0]=res[i-1][0]+grid[i][0];
        }
        //其他
        for(var i=1;i<rowLen;i++){
            for(var j=1;j<colLen;j++){
                res[i][j]=grid[i][j]+Math.min(res[i][j-1],res[i-1][j]);
            }
        }
        return res[i-1][j-1];
    };
  • 相关阅读:
    poj 2674 Linear world
    poj 3185 The Water Bowls
    The Largest Clique (uva11324)
    Proving Equivalences (LA 4287)
    强联通分量( HihoCoder 1185 )
    求点双联通分量(HihoCoder
    求桥,割点(HihoCoder
    欧拉回路
    uva10054
    表达式树(公共表达式消除 uva 12219)
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10512706.html
Copyright © 2011-2022 走看看