Leetcode OJ : Triangle 动态规划 python solution

Total Accepted: 31557 Total Submissions: 116793

 
 

Given a triangle, find the minimum path sum from top to bottom.

Each step you may move to adjacent numbers on the row below.

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

简单的动态规划

 1 import sys
 2 
 3 class Solution:
 4     # @param triangle, a list of lists of integers
 5     # @return an integer
 6     def minimumTotal(self, triangle):
 7         length = len(triangle)
 8         l = [0]
 9         l.extend([ sys.maxint for x in range(length - 1)])
10         def getLastSum(y, x):
11             return l[x] if x in range(y+1) else sys.maxint
12         for y in range(length):
13             for x in range(y, -1, -1):
14                 l[x] = triangle[y][x] + min(getLastSum(y, x), getLastSum(y, x - 1))
15         return min(l)

 

posted @ 2015-02-18 16:33  Justin.cn  阅读(210)  评论(0编辑  收藏  举报