120. Triangle

来源:互联网 发布:三菱数控车床编程实例 编辑:程序博客网 时间:2024/06/05 19:13

原网址为 https://leetcode.com/problems/triangle/description/

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.

代码:

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        if (triangle.size() == 0 || triangle[0].size() == 0) return 0;                vector<int> dist(triangle[triangle.size() - 1].size());        vector<int> tdist(triangle[triangle.size() - 1].size());                dist[0] = triangle[0][0];                for (int i = 1; i < triangle.size(); i++) {            tdist = dist;            for (int j = 0; j < triangle[i].size(); j++) {                int tmin = INT_MAX;                if (j - 1 >= 0) tmin = tdist[j - 1];                if (j < triangle[i - 1].size()) tmin = tmin > tdist[j] ? tdist[j] : tmin;                                dist[j] = tmin + triangle[i][j];            }        }                int min = INT_MAX;                for (int i = 0; i < dist.size(); i++) {            if (dist[i] < min) min = dist[i];        }                return min;    }};


原创粉丝点击