给出一个三角形(数据数组),找出从上往下的最小路径和。每一步只能移动到下一行中的相邻结点上。
比如,给你如下三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
则从上至下最小路径和为 11(即,2 + 3 + 5 + 1 = 11)
注意:
加分项:如果你可以只使用 O(n) 的额外空间(n是三角形的行数)。
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.
建立与三角形相同结构的二维数组,每格存储到达该点可达到的最小值。由上而下每一个点都比较与自己相邻的上层的两个点(边缘部位则只有一个相邻点),取数值最小的点与自身数字相加,最后得到最后一列值最小的数为结果。
代码(JavaScript):
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
var height=triangle.length;
var path=new Array();
for(var i=0;i<height;i++){
path[i]=new Array();
for(var j=0;j<i+1;j++){
path[i][j]=triangle[i][j];
}
}
console.log(path);
for(var i=1;i<height;i++){
for(var j=0;j<i+1;j++){
if(j==0){
path[i][j]+=path[i-1][j];
}
else if(j==i){
path[i][j]+=path[i-1][j-1];
}
else{
path[i][j]+=Math.min(path[i-1][j-1],path[i-1][j]);
}
}
}
console.log(path);
var min=path[height-1][0];
for(var i=0;i<height;i++){
min=Math.min(path[height-1][i],min);
}
return min;
};
本文介绍了一种解决从三角形顶部到底部寻找最小路径和的问题的方法。通过动态规划的方式,利用一个二维数组来记录到达每个节点的最小路径值,最终找到最小路径总和。
5133

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



