题目:
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).
思路:
方法一:从上到下, 下一行的结果根据上一行的路径累计和而计算。
triangle[i][j] += min(triangle[i -1 [j -1 ],triangle[i -1 ][j ] ) ,这样需要处理j=0和j=最大值。
方法二:从下往上,每一行的结果根据下面一行的路基累计和而计算。(参考大神才晓得)
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])
/** * @param {number[][]} triangle * @return {number} */ var minimumTotal = function(triangle) { for(var i=triangle.length-2;i>=0;i--){ for(var j=0;j<i+1;j++){ if(triangle[i+1][j]>triangle[i+1][j+1]){ triangle[i][j]+=triangle[i+1][j+1] }else{ triangle[i][j]+=triangle[i+1][j] } } } return triangle[0][0]; };