zoukankan      html  css  js  c++  java
  • Leetcode 120. Triangle

    Description: Given a triangle array, return the minimum path sum from top to bottom.

    For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

    Link: 120. Triangle

    Examples:

    Example 1:
    Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
    Output: 11
    Explanation: The triangle looks like:
       2
      3 4
     6 5 7
    4 1 8 3
    The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
    
    Example 2:
    Input: triangle = [[-10]]
    Output: -10

    思路: 动态规划,求从顶到底的最短路径和。dp定义为从顶到该点的最短路径和。当前点可以来自上一层的i, i-1,但注意每行两边的更新。

    class Solution(object):
        def minimumTotal(self, triangle):
            """
            :type triangle: List[List[int]]
            :rtype: int
            """
            n = len(triangle)
            if n == 0: return triangle[0][0]
            dp = [[0]*i for i in range(1,n+1)]
            # print(dp)
            dp[0][0] = triangle[0][0]
            for row in range(1, n):
                for i in range(row+1):
                    if i == 0:
                        dp[row][i] = triangle[row][i] + dp[row-1][i]
                    elif i > 0 and i < row:
                        dp[row][i] = triangle[row][i] + min(dp[row-1][i-1], dp[row-1][i])
                    else:
                        dp[row][i] = triangle[row][i] + dp[row-1][i-1]
            return min(dp[-1])

    之前看一篇讲解动态规划的,说的很对,动态规划就是防止重复计算,而把要重复的东西记录下来,方便最后答案的计算。所以找不到状态的时候,就想想什么东西要被重复记下来,可能是有用的。

    日期: 2021-04-07 再不刷图,感觉毕业要失业

  • 相关阅读:
    Java 多线程(一) 基础知识与概念
    hashMap和treeMap
    转:Java IO流学习总结
    hibernate缓存
    java aio nio bio
    java1.8新特性
    LeetCode Contiguous Array
    LeetCode Sort Characters By Frequency
    LeetCode Subarray Sum Equals K
    LeetCode Group Anagrams
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14631895.html
Copyright © 2011-2022 走看看