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;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值