题干:
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(第二行中的两个数)+第一行的数。
依次类推,我们从下往上,可以找到某一行某个数到最后一行相应的最小和,即:
result[j] = min(result[j], result[j + 1]) + triangle[size - 2 - i][j];
当循环都第一行时,则是我们所求的从上往下路径的最小和。
AC代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int size = triangle.size();
int result[triangle[size - 1].size()];
for (int i = 0; i < triangle[size - 1].size(); i ++) {
result[i] = triangle[size - 1][i];
}
for (int i = 0; i < size - 1; i ++) {
for (int j = 0; j < triangle[size - 2 - i].size(); j ++) {
result[j] = min(result[j], result[j + 1]) + triangle[size - 2 - i][j];
}
}
return result[0];
}
};