120. Triangle
题目要求
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 - 1]
或者点[i - 1, j]
,假设到达点[i, j]
的最小路径为dp(i, j)
,经过该点的代价为
Ci,j
,那么有:
dp(i,j)=⎧⎩⎨⎪⎪⎪⎪⎪⎪Ki,j,dp(i−1,j)+Ki,j,dp(i−1,j−1)+Ki,j,min{dp(i−1,j),dp(i−1,j−1)},i = 0j = 0j = iothers
时间复杂度和空间复杂度为 O(N2)
为了方便,可以在每一行的前后各加距离为正无穷的点,简化逻辑。
代码如下:
#define MAX 1000000
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int depth = triangle.size();
if (depth == 0) return 0;
int width = triangle[depth - 1].size();
vector<vector<int>> dp;
dp.push_back({MAX, triangle[0][0], MAX});
for (int i = 1; i < depth; ++i) {
dp.push_back(vector<int>(i + 3, MAX));
for (int j = 1; j <= i + 1; ++j) {
dp[i][j] = std::min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j - 1];
}
}
int min = 1000000;
for (const auto& i: dp[depth - 1]) {
if (min > i) min = i;
}
return min;
}
};
降低空间复杂度
由于每一行只依赖于上一行的结果,所以可以进行覆盖,但要记得保存 dp(i−1,j−1) 。
#define MAX 1000000
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int depth = triangle.size();
if (depth == 0) return 0;
int width = triangle[depth - 1].size();
vector<int> dp(width + 2, MAX);
dp[1] = triangle[0][0];
int min = MAX;
for (int i = 1; i < depth; ++i) {
int prev = dp[0];
for (int j = 1; j < i + 2; ++j) {
int tmp = dp[j];
dp[j] = std::min(dp[j], prev) + triangle[i][j - 1];
prev = tmp;
}
}
for (const auto& i: dp) {
if (min > i) min = i;
}
return min;
}
};