OJ-Triangle

这是Leet Code OJ上面的一道题,关于求从上到下的最小路径。

这是原题链接:https://leetcode.com/problems/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).

此题共有两种思路:

1.从上到下;

2.从下到上,这种方法需要修改初始数组(如果不重新建立数组)。

我是用第二种方法解决的:从倒数第二行开始,求出到达此元素的最小路径,覆盖原始数组此处的值。依次类推,可以求出到达最顶端元素的最小路径,即为Triangle[0][0].

(最近在复习宽带无线通信,要考试了--。感觉维特比译码用的也是这种思路,或者说此题用的是维特比译码的思路。哈哈哈~~)

C++编写。

具体代码如下:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        for(int i=triangle.size()-2;i>=0;i--)
        {
            for(int j=0;j<i+1;j++)
            {
                if(triangle[i+1][j]<triangle[i+1][j+1])
                {
                    triangle[i][j] += triangle[i+1][j];
                }
                else
                {
                    triangle[i][j] += triangle[i+1][j+1];
                }
            }
        }
        return triangle[0][0];
    }
};