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.
题意:每次沿着相邻的数往下走,找到最小的路径和。
思路:开辟一个数组,记录到达该点的最小路径值,逐行更新,算是不太经典的动态规划。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if (triangle.empty())
return 0;
vector<int> dp(triangle[triangle.size() - 1].size(), 0);
for (int i = 0; i < triangle.size(); i++){
int k = triangle[i].size() - 1;
if (k>0){
dp[k] = triangle[i][k] + dp[k - 1];
}
for (int j = k - 1; j > 0; j--){
dp[j] = triangle[i][j] + min(dp[j], dp[j - 1]);
}
dp[0] = triangle[i][0] + dp[0];
}
return *min_element(dp.begin(), dp.end());
}
};