120. Triangle

来源:互联网 发布:知行家 编辑:程序博客网 时间:2024/06/06 01:35

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.

从下往上累加,直接不需要空间复杂度,但是这样会改变引用的数组;

int minimumTotal(vector<vector<int>>& triangle) {    if (triangle.size() == 0)return 0;    for (int i = triangle.size() - 2; i >= 0; i--){        for (int j = 0; j < triangle[i].size(); j++){            triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);        }    }    return triangle[0][0];}

从上往下累加

int minimumTotal(vector<vector<int>>& triangle) {    if (triangle.size() == 0)return 0;    if (triangle.size() == 1)return triangle[0][0];    int ans = INT_MAX, n = 0;    for (int i = 1; i < triangle.size(); i++){        n = triangle[i].size();        triangle[i][0] += triangle[i - 1][0];        triangle[i][n - 1] += triangle[i - 1][n - 2];        for (int j = 1; j < n - 1; j++){            triangle[i][j] += min(triangle[i - 1][j - 1], triangle[i - 1][j]);        }    }    for (int i = 0; i < n; i++){        ans = min(ans, triangle[triangle.size() - 1][i]);    }    return ans;} 
原创粉丝点击