LeetCode 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).

题意:

给定一个三角的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];
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值