leetcode_120. Triangle

来源:互联网 发布:oa办公系统java源代码 编辑:程序博客网 时间:2024/06/05 21:12

题目:

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

动态规划问题。从下到上,每个数的最短路径都是到下面两个数的最短路径+这个数。即min(minm[i], minm[i+1])+triangle[row][i];

从下到上,第一层得到的就是到第2层的最短路的最小值加第一层的数。

代码如下:

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        int rows = triangle.size();        vector<int>minm = triangle[triangle.size()-1];        for(int row = rows - 2; row >= 0; --row){            for(int i = 0; i <= row; ++i){                minm[i] = min(minm[i], minm[i+1])+triangle[row][i];            }        }        return minm[0];    }};


0 0
原创粉丝点击