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
[
[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.
Solution
DP, from up to down, time O(n), space O(n)
略復(fù)雜,要考慮越界情況。
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
if (n < 1) {
return 0;
}
int[] minTotal = new int[n];
minTotal[0] = triangle.get(0).get(0);
for (int i = 1; i < n; ++i) {
// update minTotal[] in reverse
minTotal[i] = triangle.get(i).get(i) + minTotal[i - 1];
for (int j = i - 1; j > 0; --j) {
minTotal[j] = triangle.get(i).get(j)
+ Math.min(minTotal[j - 1], minTotal[j]);
}
minTotal[0] += triangle.get(i).get(0);
}
int min = Integer.MAX_VALUE;
for (int num : minTotal) {
min = Math.min(min, num);
}
return min;
}
}
DP, from down to up, time O(n), space O(n)
簡潔的寫法淆游,推薦项阴!
注意對于每一行椿争,需要從前向后遍歷了哦柳击!因?yàn)榍懊娴闹狄蕾囉诤竺娴闹怠?/p>
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] minTotal = new int[triangle.size() + 1];
for (int i = triangle.size() - 1; i >= 0; --i) { // go up
for (int j = 0; j <= i; ++j) { // go right!!!
minTotal[j] = triangle.get(i).get(j)
+ Math.min(minTotal[j], minTotal[j + 1]);
}
}
return minTotal[0];
}
}