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.
题目链接:https://leetcode-cn.com/problems/triangle/
思路
DP练习。
一开始思路:从尖儿向下找路,每次只记录最好的2条路。后来发现如果走到某一步时左右相邻节点值一样,这就尴尬了不知道该记录谁。
正确思路:用递归的思想,如果走到某个节点了,此时它最好的路是由前面的两条路决定的。回忆一下一维的DP题好像也是这个思路。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int dep = triangle.size();
if(dep==0) return 0;
if(dep==1) return triangle[0][0];
int res[dep+1];
res[0] = triangle[0][0];
for(int i=1; i<dep; ++i){
for(int j = i; j>=1; --j){
if(j==i) res[j] = res[j-1] + triangle[i][j];
else res[j] = min(res[j], res[j-1]) + triangle[i][j];
}
res[0] = res[0] + triangle[i][0];
}
int sum = INT_MAX;
for(int i=0; i<=dep; ++i){
sum = (res[i]<sum)?res[i]:sum;
}
return sum;
}
};
ps.数组的速度果然比vector快多了。运行结果0ms,15MB。
3506




被折叠的 条评论
为什么被折叠?



