题目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).
题目分析:
显然是动态规划的题目(当时还NC般想用贪心),关键是列出动态规划方程:
dp[i][j] = min{dp[i - 1][j - 1], dp[i - 1][j]} + triangle[i][j];
不需要保存每一个值的dp,下一行的结果仅仅需要上一层的结果,空间复杂度可以降到O(N),动态规划方程:
dp[j] = min{dp[j], dp[j + 1]} + triangle[i][j];
自底向上实现,代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int row = triangle.size();
if (row == 0)
return 0;
vector<int> dp(triangle[row - 1].size());
int i, j;
for (i = row - 1; i >= 0; i --) {
int col = triangle[row - 1].size();
for (j = 0; j < col; j ++) {
if (i == row - 1) {
dp[j] = triangle[i][j];
continue;
}
dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j];
}
}
return dp[0];
}
};
参考:
[1] http://fisherlei.blogspot.com/2013/01/leetcode-triangle.html