LeetCode 120 : Triangle

LeetCode 120 : Triangle

题目大意

给定一个数字三角形,求出从最上层运动到最下层的最短路径。

  • Description
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
  • Example
 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.

思路分析

直接从上向下选择当前最短的路径时,由于之后元素的未知,我们无法确定获得的路径是最短的,例如:
当三角中元素为: [1],[2,5],[3,4,1],[3,8,1,2]时,根据上述方法算出的路径长度为9(1+2+3+3),而实际上有更短的路径,长度为8(1+5+1+1)。
因此,可以选择从下向上的方法,从最底层开始,计算走到当前元素位置的最短路径长度,最顶层元素处获得的值就是需要的值。

相应代码

  • 初级版
int minimumTotal(vector<vector<int>>& triangle) {
        int r= triangle.size();
        for(int i=r-2;i>=0;i--){
            for(int j=0;j<triangle[i].size();j++){
                triangle[i][j] = triangle[i][j] + (triangle[i+1][j]>triangle[i+1][j+1] ? triangle[i+1][j+1] : triangle[i+1][j]);
        }
        }
        return triangle[0][0];
    }
  • 升级版
int minimumTotal(vector<vector<int>>& triangle) {
        int r = triangle.size();
        vector<vector<int>> d(r);
        for(int i=0;i<r;i++){
            d[i].resize(triangle[i].size());
        }

        for(int i=r-1;i>=0;i--){
            for(int j=0;j<triangle[i].size();j++){
                if(i==r-1){
                    d[i][j] = triangle[i][j];
                }
                else{
                    d[i][j] = triangle[i][j] + (d[i+1][j]>d[i+1][j+1] ? d[i+1][j+1] : d[i+1][j]);
                }

            }
        }
        return d[0][0];
    }

对比:两版代码的区别在于,初级版改变了原参,而升级后不需要对参数做任何修改,适应性更强。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值