Leetcode(120) 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.

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.

解法

一道典型的动态规划题:

1
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + A[i][j]

具体代码如下:

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
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int minRes = 0;
Integer[][] dp = new Integer[triangle.size()][triangle.size()];
dp[0][0] = triangle.get(0).get(0);
for (int i = 1; i < triangle.size(); i++) {
for (int j = 0; j <= i; j++) {
if (j == 0) {
dp[i][j] = dp[i - 1][j] + triangle.get(i).get(j);
} else if (j == i) {
dp[i][j] = dp[i - 1][j - 1] + triangle.get(i).get(j);
} else {
dp[i][j] = (dp[i - 1][j - 1] < dp[i - 1][j] ? dp[i - 1][j - 1] : dp[i - 1][j]) + triangle.get(i).get(j);
}
}
}
minRes = dp[triangle.size() - 1][0];
for (int j = 0; j <= triangle.size() - 1; j++) {
if (dp[triangle.size() - 1][j] < minRes) {
minRes = dp[triangle.size() - 1][j];
}
}
return minRes;
}
}

看到网上的大佬可以把二维降成一维的解题:
https://blog.csdn.net/fuxuemingzhu/article/details/82883187