Python 的 LeetCode 之旅(3):120. Triangle

120Triangle:

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.

题目大意:

给出一三角堆,要求从堆顶沿着相邻的节点移动到堆底,每个节点有其对应的值,求一条路径使得所经过的所有节点的值的和最小(每层仅经过一个节点)

解题思路:

其实这题只要求出到达每一层的每一个节点的最短路径就可以了,而且每一层的节点的最短路径只与其上一层的节点路径有关,因此所需保存的信息就是上一层的节点信息,因此额外的空间为O(n),最终返回的结果为最后一层中的最小的数。代码如下:

class Solution(object):
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        pre = [i for i in range(len(triangle))]
        pre[0] = triangle[0][0]
        cur = pre[:]
        for i in range(1,len(triangle)):
            for j in range(len(triangle[i])):
                if j - 1 >= 0 and j < len(triangle[i - 1]):
                    cur[j] = min(pre[j - 1],pre[j]) + triangle[i][j]
                elif j - 1 >= 0:
                    cur[j] = pre[j - 1] + triangle[i][j]
                else:
                    cur[j] = pre[j] + triangle[i][j]
            pre = cur[:]
        return min(cur)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值