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

code

class Solution
{
public:
    int minimumTotal(vector<vector<int>>& triangle)
    {
        if(triangle.empty()||triangle.at(0).empty())
            return -1;

        for(int i=1;i<triangle.size();++i)
        {
            for(int j=0;j<triangle.at(i).size();++j)
            {
                if(j==0)
                    triangle.at(i).at(j)+=triangle.at(i-1).at(j);
                else if(j==triangle.at(i).size()-1)
                    triangle.at(i).at(j)+=triangle.at(i-1).at(j-1);
                else
                    triangle.at(i).at(j)+=min(triangle.at(i-1).at(j),triangle.at(i-1).at(j-1));
            }
        }
        return *min_element(triangle.at(triangle.size()-1).begin(),triangle.at(triangle.size()-1).end());
    }
};

 

上一篇:Leetcode 120. 三角形最小路径和(DAY 28) ---- 动态规划学习期


下一篇:LeetCode.976-周长最大的三角形(Largest Perimeter Triangle)