您的位置:首页 > 其它

LeetCode - 120. Triangle

2016-09-25 17:20 309 查看
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 [code]11
(i.e., 2 + 3 + 5 + 1 = 11).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.思路:简单DP,把到每一个点的最优路径算出来,利用上面算好的结果。最后选最后一层的最优解。[/code]
1,动态规划。到第i层的第k个顶点的最小路径长度表示为f(i,k),则f(i, k) = min{f(i-1,k), f(i-1,k-1)} + d(i, k); 其中d(i, k)表示原来三角形数组里的第i行第k列的元素。则可以求得从第一行到最终到第length-1行第k个元素的最小路径长度,最后再比较第length-1行中所有元素的路径长度大小,求得最小值。2,本题主要关心的是空间复杂度不要超过n。3,注意边界条件——每一行中的第一和最后一个元素在上一行中只有一个邻居。而其他中间的元素在上一行中都有两个相邻元素。代码:
import java.util.*;
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.get(0) == null)
return 0;

int iLen = triangle.size();

for (int i=1; i<iLen; i++) {
int jLen = triangle.get(i).size();
for (int j=0; j<jLen; j++) {
if (j == 0) {
triangle.get(i).set(0, triangle.get(i).get(0) + triangle.get(i-1).get(0));
}
else if (j == jLen - 1) {
triangle.get(i).set(j, triangle.get(i).get(j) + triangle.get(i-1).get(j-1));
}
else {
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i-1).get(j-1), triangle.get(i-1).get(j)));
}
}
}

return Collections.min(triangle.get(iLen-1));
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: