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://oj.leetcode.com/problems/triangle/
题目:给定一个三角形,找出从顶部到底部的最短路径和。每一步你可以移动到下一行的邻接数字。
思路:最初的理解是:最短路径和可以看成是找出每一行中的最小值,最后求和。
public int minimumTotal1(List<List<Integer>> triangle) {
int sum = 0;
for (int i = 0; i < triangle.size(); i++) {
int min = triangle.get(i).get(0);
for (int j = 0; j < triangle.get(i).size(); j++) {
if (triangle.get(i).get(j) < min)
min = triangle.get(i).get(j);
}
sum += min;
}
return sum;
} public int minimumTotal(List<List<Integer>> triangle) {
for(int i = triangle.size() - 2; i >= 0; i--)
{
for(int j = 0; j < triangle.get(i).size(); j++)
{
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
}
}
return triangle.get(0).get(0);
}
LeetCode——Triangle,布布扣,bubuko.com
原文:http://blog.csdn.net/laozhaokun/article/details/37735623