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).
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int r = triangle.size();
//注意边界条件,写代码之前都先判断一下边界条件
if(!r || !triangle[0].size())return 0;
int len = triangle[r - 1].size();
int *rst = new int[len];
//从最后一行开始,先用最后一行为结果赋值
//因为每次计算第[ij]的结果是之和rst[j]及[j+1]相关,更新的是rst[j],
//不会影响下次计算相关的额rst[j+1]及rst[j+2]所以可以再远rst数组的基础上计算,不用再开额外辅助空间
for(int i = 0; i < len; i++)rst[i] = triangle[r - 1][i];
for(int row = r - 1; row >= 1; row--)
{
int col_len = triangle[row - 1].size();
for(int col = 0; col < col_len; col++)
rst[col] = triangle[row - 1][col] + min(rst[col], rst[col + 1]);
}
int rtv = rst[0];
delete[] rst;
return rtv;
}
};