题目
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.
题解
这又是一道比较简单的动态规划的题目了。设dp(i, j)为经过第i层第j点到达顶点的代价,则dp(i, j) = triangle(i, j) + min(dp(i + 1, j), dp(i+1, j+1))。由于空间复杂度要求是O(n),我们之间在原数组上操作,给出一个空间复杂度为O(1)的算法。
代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for (int i = triangle.size() - 2; i >= 0; i--) {
List<Integer> list = triangle.get(i);
List<Integer> next = triangle.get(i + 1);
for (int j = 0; j <= i; j++) {
list.set(j, list.get(j) + Math.min(next.get(j), next.get(j + 1)));
}
}
return triangle.get(0).get(0);
}
}