Leetcode Triangle Python实现

Leetcode Triangle Python实现

标签(空格分隔): leetcode 算法


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.

原题路径:
https://oj.leetcode.com/problems/triangle/

结题思路:

题目中的三角形不适合找到解题思路,把他看成一个矩阵的左下角。
该题就成了一个方格路径的问题。
自上而下,上方的每个元素只能和其正下方和右下方的元素相加。用一个列表记录当前路径(累加值),最后取最小值即可。

具体代码:

class Solution:
# @param triangle, a list of lists of integers
# @return an integer
def minimumTotal(self, triangle):
    if len(triangle) < 1:
        return
    elif len(triangle) == 1:
        return triangle[0][0]
    
    # len>1
    paths = triangle[0]  # paths 记录当前的所有路径值
    length = len(triangle)
    for i in range(1, length):
        data = triangle[i]
        size = len(paths)
        temp = []  # temp用于记录新的路径值
        for j in range(size):
            currentValue = paths[j]
            if j == 0:
                temp.append(currentValue + data[j])  # 正下
                temp.append(currentValue + data[j + 1])  # 右下
            else:
                if (currentValue + data[j]) < temp[j]:
                    temp[j] = currentValue + data[j]
                temp.append(currentValue + data[j + 1])
        paths = temp
    return min(paths)


if __name__ == '__main__':
    s = Solution()
    ans = s.minimumTotal([
     [2],
    [3, 4],    [6, 5, 7],   [4, 1, 8, 3] ])
#     ans = s.minimumTotal([[2]])
    print (ans)
posted @ 2014-09-01 14:23  Damian Zhou  阅读(334)  评论(0编辑  收藏  举报