LeetCode 120. Triangle

来源:互联网 发布:python 冒泡排序 编辑:程序博客网 时间:2024/05/16 23:44

LeetCode 120. 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.

分析

我们可以把数值看做路径的长度。
这是一个最短路径问题,DP算法足矣。
但要注意,如果自上而下进行运算会使运算路径发散,从而超时。所以我们采用自下而上的方式。

具体代码实现如下:

class Solution { public:    int minimumTotal(vector<vector<int>>& triangle) {        while (!triangle.empty())        {            int v_index = triangle.size() - 1;            if (v_index == 0)break;            for (int num_index = 0; num_index < triangle[v_index].size() - 1; num_index++)            {                triangle[v_index - 1][num_index] += min(triangle[v_index][num_index] , triangle[v_index][num_index+1]);            }            triangle.pop_back();        }        return triangle[0][0];    }};
原创粉丝点击