[Lintcode]109. Triangle/[Leetcode]120. Triangle

本文探讨了在给定三角形结构中寻找从顶部到底部的最小路径和问题,使用动态规划方法解决,并提供了具体代码实现。通过逆向思维,从底部开始计算,将每个节点的最小路径和更新为到其下方两节点中较小值加自身值。

109. Triangle/120. Triangle

  • 本题难度: Medium
  • Topic: Dynamic Programming

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.

Example
example 1
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).

example 2
Given the following triangle:

[
[2],
[3,2],
[6,5,7],
[4,4,8,1]]
The minimum path sum from top to bottom is 12 (i.e., 2 + 2 + 7 + 1 = 12).

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

我的代码

class Solution:
    """
    @param triangle: a list of lists of integers
    @return: An integer, minimum path sum
    """
    def minimumTotal(self, triangle):
        # write your code here
    
        l = len(triangle)
        if l == 0:
            return 0
        if l == 1:
            return triangle[0][0]
        res = triangle[-1]
        for i in range(l-2,0,-1):
            for j in range(len(triangle[i])):
                res[j] = triangle[i][j]+min(res[j],res[j+1])
        return triangle[0][0]+min(res[:2])

思路
从下往上,每一个都是到达下面相邻的两个元素中路径中较小的加上当前元素之和,作为到达该位置的最小路径

      [2],     ^         [2]
    [3, 4],    |       [9, 10,          10, 3]
   [6, 5, 7],  |     [7, 6, 10,         3]
  [4, 1, 8, 3] |   [4, 1,  8, 3]

注意特殊情况:
只有一个元素和空三角形

  • 时间复杂度 O(n^2)
  • 空间复杂度 O(n)

转载于:https://www.cnblogs.com/siriusli/p/10376330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值