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];
}
};