leetcode-120. Triangle
题目:
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).
思路就是传统的DP,只不过传统的思路都是使用矩阵去做,这里也是类似的,但是需要注意下标是否准确就好。
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] list = new int[triangle.size()];
int[] cur = new int[triangle.size()];
if(triangle.size()<1)return 0;
list[0] = triangle.get(0).get(0);
if(triangle.size()==1) return list[0];
for(int i = 1 ; i < triangle.size() ; i++){
cur = new int[triangle.size()];
for(int j = 0 ; j <= i ;j++){
cur[j] = Math.min((j>0 ? list[j-1] : Integer.MAX_VALUE),(j<triangle.get(i-1).size()? list[j]:Integer.MAX_VALUE))+triangle.get(i).get(j);
}
list = cur;
System.out.println(Arrays.toString(list));
}
int ret = Integer.MAX_VALUE;
for(int x : cur)
if(ret>x) ret =x;
return ret;
}
}