题目大意
给定一个数字三角形,求出从最上层运动到最下层的最短路径。
- Description
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
- Example
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,5],[3,4,1],[3,8,1,2]时,根据上述方法算出的路径长度为9(1+2+3+3),而实际上有更短的路径,长度为8(1+5+1+1)。
因此,可以选择从下向上的方法,从最底层开始,计算走到当前元素位置的最短路径长度,最顶层元素处获得的值就是需要的值。
相应代码
- 初级版
int minimumTotal(vector<vector<int>>& triangle) {
int r= triangle.size();
for(int i=r-2;i>=0;i--){
for(int j=0;j<triangle[i].size();j++){
triangle[i][j] = triangle[i][j] + (triangle[i+1][j]>triangle[i+1][j+1] ? triangle[i+1][j+1] : triangle[i+1][j]);
}
}
return triangle[0][0];
}
- 升级版
int minimumTotal(vector<vector<int>>& triangle) {
int r = triangle.size();
vector<vector<int>> d(r);
for(int i=0;i<r;i++){
d[i].resize(triangle[i].size());
}
for(int i=r-1;i>=0;i--){
for(int j=0;j<triangle[i].size();j++){
if(i==r-1){
d[i][j] = triangle[i][j];
}
else{
d[i][j] = triangle[i][j] + (d[i+1][j]>d[i+1][j+1] ? d[i+1][j+1] : d[i+1][j]);
}
}
}
return d[0][0];
}
对比:两版代码的区别在于,初级版改变了原参,而升级后不需要对参数做任何修改,适应性更强。