zoukankan      html  css  js  c++  java
  • leetcode 【 Triangle 】python 实现

    题目

    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.

    代码:oj测试通过 Runtime: 82 ms

     1 class Solution:
     2     # @param triangle, a list of lists of integers
     3     # @return an integer
     4     def minimumTotal(self, triangle):
     5         # special case
     6         if len(triangle)==0:
     7             return 0
     8         # dp visit
     9         LEVEL = len(triangle)
    10         dp = [0 for i in range(LEVEL)]
    11         for i in range(LEVEL):
    12             for j in range(len(triangle[i])-1,-1,-1):
    13                 if j==len(triangle[i])-1 :
    14                     dp[j] = dp[j-1] + triangle[i][j]
    15                 elif j==0 :
    16                     dp[0] = dp[0] + triangle[i][0]
    17                 else:
    18                     dp[j] = min(dp[j-1],dp[j]) + triangle[i][j]
    19         return min(dp)

    思路

    典型的动态规划,思路跟Unique Path类似,详情见

    http://www.cnblogs.com/xbf9xbf/p/4250359.html

    另,这道题还有一个bonus,如何用尽量少的额外空间。

    一般的dp思路是,定义一个O(n)的空间,跟三角形等大小的额外空间。

    这里只用三角形最底层那一层的大小的空间。

    遍历第i层时,利用 dp[1:len(triangle[i])] 的空间存储开始节点到第i层各个节点的最小和。

    这里注意:从后往前遍历可以节省数组空间。这是Array的一个常见操作技巧,详情见

    http://www.cnblogs.com/xbf9xbf/p/4240257.html

    连续刷刷题,能把前后的技巧多关联起来,对代码的能力提升有一定的帮助。

  • 相关阅读:
    [转]测试的基本概念
    记录
    flash 与 程序通讯
    怎么正确的建立项目
    安装包的制作
    JS
    页面刷新定位
    [转]C#处理XML
    MSN机器人
    报表 的使用
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4251195.html
Copyright © 2011-2022 走看看