算法作業_27(2017.6.8第十六週)

120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjachttp://write.blog.csdn.net/posteditent 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).

解析:動態規劃的題目,求一個三角形二維數組從頂端到地段的最小路徑。我們可以從底端(倒數第二行)開始,採用又底向上的方法。

狀態轉移方程爲:dp[i][j] = min(dp[i+1][j] + dp[i+1][j+1]) +dp[i][j]。dp[0][0]就是答案,代碼如下:

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


 

120. Triangle

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