zoukankan      html  css  js  c++  java
  • 64. Minimum Path Sum

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

    Note: You can only move either down or right at any point in time.

    Example:

    Input:
    [
      [1,3,1],
      [1,5,1],
      [4,2,1]
    ]
    Output: 7
    Explanation: Because the path 1→3→1→1→1 minimizes the sum.

    class Solution(object):
        def minPathSum(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            n = len(grid)
            m = len(grid[0])
            # 初始化二维数组
            dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
            # 遍历二维数组
            for i in xrange(0, n):
                for j in xrange(0, m):
                    if i == 0 and j == 0:
                        dp[0][0] = grid[0][0]
                    # 上边只有一条路径可走,上边一行等于前面的格子相加
                    elif i == 0:
                        dp[i][j] = dp[i][j-1] + grid[i][j]
                    # 左边之后一条路径可走,左边的一行等于前面的格子相加
                    elif j == 0:
                        dp[i][j] = dp[i-1][j] + grid[i][j]
                    #其余有2条路径可走,取最小值
                    else:
                        dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
            return dp[n-1][m-1]
  • 相关阅读:
    GlusterFS安装部署
    glusterfs peer失败
    GlusterFs 启动报错
    利用idea反编译jar包
    hive 错误记录 之moveing 失败
    节点不可用,显示noReady
    kafka 配置认证与授权
    flink (2) 读取kafka数据
    Flink (1) 安装部署
    redis the cluster is down
  • 原文地址:https://www.cnblogs.com/boluo007/p/12421327.html
Copyright © 2011-2022 走看看