题目:
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.
思路:
本题也是典型的动态规划题目,有点类似于Pascal Triangle。比较直观的思路是从上往下扫描,但是更巧妙的思路是从下往上扫描。不过无论如何,算法的时间复杂度都是O(n),空间复杂度也为O(n)。
代码:
1、从上往下扫描:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle)
{
if(triangle.size() == 0) {
return 0;
}
vector<int> dp;
dp.push_back(triangle[0][0]);
for (int i = 1; i < triangle.size(); ++i) {
vector<int> temp(dp);
dp[0] = temp[0] + triangle[i][0];
for(int j = 1; j <= i - 1; ++j) {
dp[j] = std::min(temp[j - 1], temp[j]) + triangle[i][j];
}
dp.push_back(temp[i - 1] + triangle[i][i]);
}
int minValue = std::numeric_limits<int>::max();
for(int i = 0; i < dp.size(); ++i) {
if(dp[i] < minValue) {
minValue = dp[i];
}
}
return minValue;
}
};
2、从下往上扫描:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size() == 0) {
return 0;
}
int len = triangle.size();
vector<int> dp(triangle[len - 1].size());
for(int i = 0; i < dp.size(); i++) {
dp[i] = triangle[len-1][i];
}
for(int i = len - 2; i >= 0; i--) {
for(int j = 0 ; j < triangle[i].size(); j++) {
dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j];
}
}
return dp[0];
}
};