题目: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.
题目详情见 https://leetcode.com/problems/triangle/#/description
解析1 :自顶向下,令 f[i][j] 表示从顶部元素到 triangle 中第 i 行第 j 列的最小路径长度,则
但是需要注意当 j 为 第 i 行的第一个元素时,
当 j 为第 i 行的最后一个元素时,
则从顶部到底部的最小路径和为 f[triangle.size()−1][j] 的最小值
代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(n)
// 自顶向下
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
const int n = triangle.size();
vector<int> f(n, 0); // f 表示顶部元素到某一行各个位置的最小距离
f[0] = triangle[0][0]; // f[0] 的初值
for (int i = 0; i < triangle.size() - 1; ++i) {
// 根据顶部元素到第 i 行各个位置的最小距离
// 推断出 到 i + 1 行各个位置的最小距离。
int last_index = triangle[i + 1].size() - 1;
// 逆序搜索 triangle 中第 i+1 行的各个元素
for (int j = last_index; j >= 0; --j) {
if (j == 0) f[j]= f[j] + triangle[i + 1][j];
else if (j == last_index) f[j] = f[j - 1] + triangle[i + 1][j];
else
f[j] = min(f[j - 1], f[j]) + triangle[i + 1][j];
}
}
int min_sum = f[0];
for (int i = 1; i < f.size(); ++i)
min_sum = min(min_sum, f[i]);
return min_sum;
};
解析2:自底向上,令 f[i][j] 表示从最底行到 triangle 中第 i 行第 j 列的最小路径和,则
则显然易见,从顶部到底部的最小路径和为 f[0][0]
相比如自顶向下,自底向上方法代码更为紧凑和简洁,因为不需要进行分类讨论,代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(n)
// 自底向上,相比如自顶向下,代码更为紧凑简洁
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
const int n = triangle.size();
// f 表示从最底行各个位置到 triangle 中某一行各个位置的最小距离
// f 的初始值为最底行的元素
vector<int> f(triangle[n - 1].begin(), triangle[n - 1].end());
for (int i = triangle.size() - 1; i > 0; --i) {
// 根据最低行各个位置到第 i 行的各个位置最小距离
// 推出到第 i-1 行的各个位置最小距离
int last_index = triangle[i - 1].size() - 1;
for (int j = 0; j <= last_index; ++j)
f[j] = min(f[j], f[j + 1]) + triangle[i - 1][j];
}
return f[0];
}
};