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).
动态规划题目
定义一个二维数组记录当前位置到最后一行的数值,然后从下往上算,即s[i][j]代表i,j到最后一行的最小值,这里 选择从下往上是要比从上往下好的
如果从上往下算的话需要判断上一行此处的值是否存在,因为是三角形
* 公式:s[i][j] = t[i][j] + min(s[i+1][j] ,s[i+1][j+1])
* 最后s[0][0]就是最后的结果
public int minimumTotal(List<List<Integer>> triangle) {
int l = triangle.size();
int n = triangle.get(l-1).size();
//特殊情况
if (l ==0 || n==0)
return 0;
int[][] res = new int[l][n];
//初始条件
for (int i = 0;i < n;i++)
{
res[l-1][i] = triangle.get(l-1).get(i);
}
//动态规划主体
for (int i = l-2; i >= 0; i--) {
for (int j = 0;j < triangle.get(i).size();j++)
{
res[i][j] = Math.min(res[i+1][j],res[i+1][j+1]) + triangle.get(i).get(j);
}
}
return res[0][0];
}