ITPub博客

首页 > > > [LeetCode] Triangle

[LeetCode] Triangle

作者:Ruiyuan Li 时间:2015-08-12 00:00:00 0 删除 编辑

Triangle

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.

解题思路:

动态规划。用d来记录从根到页的最短路径,i为当前行数。则有

d[j] = d[j-1] + triangle[i][j],j==i时

d[j] = d[0] + triangle[i][0], j==0时

d[j] = min(d[j-1], d[j]) + triangle[i][j],其他。

注意计算d[j]时,会用到上一次的d[j-1],因此可以按d[i..0]的顺序来计算。

class Solution {
public:
    int minimumTotal(vector>& triangle) {
        int n = triangle.size();
        if(n==0){
            return 0;
        }
        if(n==1){
            return triangle[0][0];
        }
        int d[n];
        d[0] = triangle[0][0];
        for(int i=1; i=0; j--){    //这里从由高到低
                if(j==i){
                    d[j] = d[j-1] + triangle[i][j];
                }else if(j==0){
                    d[j] = d[0] + triangle[i][0];
                }else{
                    d[j] = min(d[j-1], d[j]) + triangle[i][j];
                }
            }
        }
        
        int minPath = d[0];
        for(int i=1; i


转载请注明: » [LeetCode] Triangle
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825