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

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

原文地址:https://www.cnblogs.com/xbf9xbf/p/4251195.html