题目描述
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 is11(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问题的时候可以考虑从后往前处理。
layer[]从倒数第一行开始改变,更新公式:i层的长度加上从最底层到i+1层的最短长度。
import java.util.*;
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
int len = triangle.size();
int [] layer = new int [len];
ArrayList <Integer> temp = triangle.get(len - 1);
for(int i = 0; i < temp.size(); ++i){
layer[i] = temp.get(i);
}
int nowLayer = len - 2;
while(nowLayer >=0){
temp = triangle.get(nowLayer);
for(int i = 0; i < temp.size(); ++i){
layer[i] = (layer[i] > layer[i + 1]? layer[i+1] : layer[i]) + temp.get(i);
}
nowLayer--;
}
return layer[0];
}
}