本文是LeetCode的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.
思路1(递归求解):给一个三角形数组,找出一条路径且该路径上的所有数字和最小,从一个数字只能走到它下方的两个数字之一。
思路2:首先想到的就是递归求解,与在二叉树中找出一个最小路径和几乎一样。
/ 0, if i >= triangle.size()
d[i][j] = - min(d[i+1][j], d[i+1][j+1]) + triangle[i][j]
即递归的出口是i >= triangle.size(),否则就递归求解其下一行的最小值。
但题目有限制说只能使用O(n)大小的空间,并且该方法运行超时。
利用一个大小为n的数组,保存每一层的最小值,滚动计算每一层的最小值。有自顶向下和自底向上两种方案,其中自底向上更直观,这里以此为例说明。
将辅助数组初始化为triangle最后一行的值(图中最左侧一列代表辅助数组dp[triangle.size()])。
从下向上更新,dp[j] = min(dp[j], dp[j+1]) + triangle[i][j]。
,
,
dp[0]就是所求结果。
当然还能再优化,不需要辅助数组,即直接将结果保存到原数组中,解法相同。
源码:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
int size = triangle.size();
vector<int> dp(size);
for(int j = 0; j < size; j++){
dp[j] = triangle[size-1][j];
}
for(int i = size-2; i >= 0; i--){
for(int j = 0; j <= i; j++){
dp[j] = min(dp[j], dp[j+1]) + triangle[i][j];
}
}
return dp[0];
}
};