Star

LeetCode 120.Triangle

Question

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

1
2
3
4
5
6
[
[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.

Explanation

动态规划的基本题。主要就是要给每个pos都有一个找到最小值,逐层找到最后一个。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) return -1;
if (triangle.get(0) == null || triangle.get(0).size() == 0) return -1;
int n = triangle.size();
int[][] f = new int[n][n];
f[0][0] = triangle.get(0).get(0);
for (int i=1; i<n; i++) {
f[i][0] = f[i-1][0] + triangle.get(i).get(0);
f[i][i] = f[i-1][i-1] + triangle.get(i).get(i);
}
for (int i=1; i<n; i++) {
for(int j=1; j<i; j++) {
f[i][j] = Math.min(f[i-1][j-1], f[i-1][j]) + triangle.get(i).get(j);
}
}
int best = f[n-1][0];
for (int i=1; i<n; i++) {
best = Math.min(best, f[n-1][i]);
}
return best;
}
}