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).
题目:在三角路径中找出从底部到头部的最短路径之和
思路:初始化minNums[n]为数据triangle[][]的最后一行。其中最后一行的每两个数字能到达上一行的一个数字,到最底层的最小路径和就是他们自己本身。从倒数第二行开始往上,从左向右循环计算并更新minNums的值,最后minNums[0]就是我们要的答案,因为最后的一行只有一个数。
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
var minNums = triangle[triangle.length-1];
for(let i=triangle.length-2;i>=0;i--){
for(let j=0;j<triangle[i].length;j++){
minNums[j] = (minNums[j] < minNums[j + 1] ? minNums[j] : minNums[j + 1])+ triangle[i][j];
}
}
return minNums[0];
};