Triangle

Description

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

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

Method

这是一个动态规划问题,用一个数组存入每一个数字的最优值,然后求最后一行的最小值即可。
具体流程如下:

  1. 初始dp[0][0] = triangle.get(0).get(0)
  2. dp[i][j]会等于相邻父亲数字里最小值加上他本身的值。如果是端点则直接等于父亲数字的最优值加上它本身。
  3. 求最后一行的最小值。

Solution

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