您的位置:首页 > 其它

LeetCode 120. Triangle

2016-09-05 18:37 239 查看
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.

题目链接

题意:多行数据,从第一行到最后一行,每行选一个。求和的最小值。要求对于第i行第j个数据,那么它下面的一行(第i+1行)只能选择第j个或者第j+1个元素。



动态规划的状态转移方程:f[ i, j ]=f[ i, j ]+ min { f[ i-1, j-1 ], f[ i-1, j ]}

从上往下遍历时,把 f 转换为一维数组会有问题。采用从下向上遍历。

状态转移方程变为:f[ i, j ]=f[ i, j ]+ min { f[ i+1, j ], f[ i+1, j+1]}

         f[ j ]=f[ j ]+ min { f[ j ], f[ j+1 ]}

class Solution {
public:
int minimumTotal(vector<vector<int> >& triangle) {
vector<int> minvec=triangle.back();
for(int layer=triangle.size()-2;layer>=0;layer--){
for(int j=0;j<=layer;j++)
minvec[j]=triangle[layer][j]+min(minvec[j],minvec[j+1]);
}
return minvec[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: