leetcode_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).

動態規劃問題。從下到上,每個數的最短路徑都是到下面兩個數的最短路徑+這個數。即min(minm[i], minm[i+1])+triangle[row][i];

從下到上,第一層得到的就是到第2層的最短路的最小值加第一層的數。

代碼如下:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int rows = triangle.size();
        vector<int>minm = triangle[triangle.size()-1];
        for(int row = rows - 2; row >= 0; --row){
            for(int i = 0; i <= row; ++i){
                minm[i] = min(minm[i], minm[i+1])+triangle[row][i];
            }
        }
        return minm[0];
    }
};


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