[LeetCode]-Triangle 求三角形中从顶到底最短距离

Triangle


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


分析:可以将问题分解考虑,从低至顶的分析方法。

      设状态f[i][j],表示点(i,j)到顶部的距离,则f[i][j]=min(f[i-1][j-1],f[i-1][j])+(i,j),当然最左和最右端的计算方式稍有变化。最后找出最小值即可。

采用滚动数组的方式,由于下层只和上层有关系,所以只需要记录上层的信息即可,这样就把O(n^2)的空间复杂度压缩成了O(n)。
class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        int n=triangle.size();
        vector<int> f(n);
        
        f[0]=triangle[0][0];
        for(int i=1;i<n;i++){
            for(int j=triangle[i].size()-1;j>=0;j--){
                int mn;
                if(j==0){
                    mn=f[j];
                }
                if(j==i){
                    mn=f[j-1];
                }
                else{
                    mn=min(f[j-1],f[j]);
                }
                f[j]=mn+triangle[i][j];
            }
        }
        
        int min_sum=f[0];
        for(int i=1;i<n;i++)
            if(min_sum>f[i])min_sum=f[i];
        return min_sum;
    }
};


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值