1. 程式人生 > >LeetCode題庫解答與分析——#120. 三角形最小路徑和Triangle

LeetCode題庫解答與分析——#120. 三角形最小路徑和Triangle

給出一個三角形(資料陣列),找出從上往下的最小路徑和。每一步只能移動到下一行中的相鄰結點上。

比如,給你如下三角形:

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

則從上至下最小路徑和為 11(即,2 + 3 + 5 + 1 = 11)

注意:

加分項:如果你可以只使用 O(n) 的額外空間(n是三角形的行數)。

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).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

個人思路:

建立與三角形相同結構的二維陣列,每格儲存到達該點可達到的最小值。由上而下每一個點都比較與自己相鄰的上層的兩個點(邊緣部位則只有一個相鄰點),取數值最小的點與自身數字相加,最後得到最後一列值最小的數為結果。

程式碼(JavaScript):

/**
 * @param {number[][]} triangle
 * @return {number}
 */
var minimumTotal = function(triangle) {
    var height=triangle.length;
    var path=new Array();
    for(var i=0;i<height;i++){
        path[i]=new Array();
        for(var j=0;j<i+1;j++){
            path[i][j]=triangle[i][j];
        }
    }
    console.log(path);
    for(var i=1;i<height;i++){
        for(var j=0;j<i+1;j++){
            if(j==0){
                path[i][j]+=path[i-1][j];
            }
            else if(j==i){
                path[i][j]+=path[i-1][j-1];
            }
            else{
                path[i][j]+=Math.min(path[i-1][j-1],path[i-1][j]);
            }            
        }
    }
    console.log(path);
    var min=path[height-1][0];
    for(var i=0;i<height;i++){
        min=Math.min(path[height-1][i],min);
    }
    return min;
};