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

Accepted

165,027

Submissions

434,961

class Solution {
public:

int minimumTotal(vector<vector<int>>& triangle) 

    {

        int length=triangle.size();

        if(length==0)return 0;

        if(length==1)return triangle[0][0];  

        vector<int> sum=triangle[triangle.size()-1];

        

        for(int i=triangle.size()-2;i>=0;i--)

        {

            for(int j=0;j<triangle[i].size();j++)

            {

                sum[j]=min(triangle[i][j]+sum[j],triangle[i][j]+sum[j+1]);

            }

        }

        return sum[0];

    }

};

動態規劃自底向上,且以原本的二維矩陣作爲更新的最終矩陣不斷更新,以此減少空間複雜度。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章