4.10 leetcode -10 triangle

来源:互联网 发布:淘宝天猫店铺怎么申请 编辑:程序博客网 时间:2024/05/18 12:37
题目描述

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 is11(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.


triangle..本命题啊。。这个题贪心肯定有问题的,只能动归,每个节点记录着自己最大的点即可。

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

原创粉丝点击