LeetCode 120.Triangle 解题分析

题目来源:

https://leetcode.com/problems/triangle/description/

题目描述:

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

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.

题意分析:

给一个类似上图所示的三角形,找一个从三角形顶部到到底部的路径,使路径上的数字相加最小。在路径的选择中,只能选择下一行与目前数字相邻的两个数字作为下一步。

解题思路:

选择自底向上的方法,从倒数第二行开始,计算这行每个元素到下一层的最小路径。比如上图中的例子,倒数第二行中第一个元素(6)到下一层(底层)的最小路径是6+1 = 7,然后更新这个位置的数字为7,第二个元素(5)的最小路径是5+1 = 6,更新这个位置的数字为6,第三个元素(7)的最小路径7+3 = 10,更新此位置的数字为10。然后继续向上执行相同的动作。

实现代码(Python3):

class Solution:
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        for row in range(len(triangle)-2, -1, -1):
            for col in range(len(triangle[row])):
                triangle[row][col] += min(triangle[row+1][col], triangle[row+1][col+1])
        return triangle[0][0]

提交结果:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值