p120

LeetCode p120 Triangle 题解

1.题目:

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).

题意:

求一三角状数组,从顶部到底部的路径中,和值最小的那条路径的和值。

2.解题思路:

从底部往上走,每次累加自己相邻底部的最小值,见代码。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int len = triangle.size();
if (len < 1)
return 0;
for (int i = len - 2; i >= 0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
int a = Math.min(triangle.get(i + 1).get(j), triangle
.get(i + 1).get(j + 1));
triangle.get(i).set(j, triangle.get(i).get(j) + a);
}
}

return triangle.get(0).get(0);
}
}

4.一些总结: