Convert Sorted List to Binary Search Tree @ LeetCode (Python)
Path Sum II @ LeetCode (Python)

Triangle @ LeetCode (Python)

kitt posted @ 2014年3月08日 12:26 in LeetCode , 2680 阅读

动态规划, 使用两个数组, dp记录当前行信息, oldDp记录上一行信息。dp[i]的含义是从顶端走到当前行dp[i]这个位置的最小路径和。

class Solution:
    # @param triangle, a list of lists of integers
    # @return an integer
    def minimumTotal(self, triangle):
        length = len(triangle)
        dp = [0 for i in xrange(length)]
        for row in triangle:
            oldDp = dp[:]
            for i in xrange(len(row)):
                if i == 0: 
                    dp[i] = oldDp[i] + row[i]
                elif i == len(row) - 1:
                    dp[i] = oldDp[i-1] + row[i]
                else:
                    dp[i] = min(oldDp[i], oldDp[i-1]) + row[i]
        return min(dp)

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter