120. Triangle(js)

120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

题意:给定一个三角形的二维数组,求数组顶部到底部的权值最小的连续路径

代码如下:

/**
 * @param {number[][]} triangle
 * @return {number}
 */
//每走一步要保存上一步的索引
var minimumTotal = function(triangle) {
    
    if(triangle.length===0) return 0;
    
   var res=[];
    for(var i=0;i<=triangle.length;i++){
        res.push(0);
    }
  
    for(var i=triangle.length-1;i>=0;i--){
       for(var j=0;j<triangle[i].length;j++){
           res[j]=Math.min(res[j+1],res[j])+triangle[i][j];
       }
    }
    return res[0];
  
};

 

posted @ 2019-05-07 22:12  mingL  阅读(120)  评论(0编辑  收藏  举报