题目描述
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.
思路
还是一道动态规划的题,可能比较麻烦的是思考这个数据结构到底是什么样子的。其实虽然画的是一个等腰三角形,其实存储的时候是一直角三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
接下来确定递推方程:
假设s(a,b)表示存储在a,b位置的值。f(a,b)表示该位置到最后一行的最小的和。
则f(a,b)=min(s(a,b)+f(a+1,b),s(a,b)+f(a+1,b+1))
为了节省存储空间可以让f(a,b)变为一个一维数组,没换一行进行覆盖,然后最后需要保存的就是f(0,0)所对应值
代码
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size()==0||triangle[0].size()==0)
return 0;
vector<int> mins(triangle.back());
int i,j;
for(i=triangle.size()-2;i>=0;i--){
for(j=0;j<triangle[i].size();j++){
mins[j]=std::min(triangle[i][j]+mins[j],triangle[i][j]+mins[j+1]);
}
}
return mins[0];
}
};