题目:
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).
给定一个三角的list,然后其中的每一行都是类似于三角形,并且上下两行之间的元素只能和相邻的元素相加,求从头到底部的节点路径中和最小的一条路径。这道题一开始我没想到用动态规划来做。其实后来发现是一道很典型的动态规划题,走到每一行上的每一个节点,都和上一行的对应的相邻的节点有关系,所以可以把上一层的每一个节点和都保存在一个二维数组中,然后和走到这一行的节点的值相加,得到相应的结果。
public class Solution
{
public int minimumTotal(List<List<Integer>> triangle)
{
if(triangle == null)
return 0;
int height = triangle.size();
int[][] nums = new int[height][height];
nums[0][0] = triangle.get(0).get(0);
for(int i = 1; i < height; i++)
{
for(int j = 0; j <= i; j++)
{
if(j!= 0 && j != i)
nums[i][j] = Integer.min(nums[i-1][j],nums[i-1][j-1]) + triangle.get(i).get(j);
else if(j == 0) //但是这里要考虑第一行的第一个元素
nums[i][j] = nums[i-1][0] + triangle.get(i).get(j);
else if(j == i) //每一行最后的那个元素也得考虑
nums[i][j] = nums[i-1][j-1] + triangle.get(i).get(j);
}
}
Arrays.sort(nums[height-1]);
return nums[height-1][0];
}
}