zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):064-Minimum Path Sum


    题目来源


    https://leetcode.com/problems/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.


    题意分析


    Input:a matrix with weight

    Output:the minimum sum of the path from top-left to down-right

    Conditions:经过路径和最小,只能向右或向下


    题目思路


    和上题一样采用动态规划,动态方程几乎没变,dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]

    初始化第一行和第一列直接用grid和前一个位置的值即可


    AC代码(Python)


     1 class Solution(object):
     2     def minPathSum(self, grid):
     3         """
     4         :type grid: List[List[int]]
     5         :rtype: int
     6         """
     7         m = len(grid)
     8         n = len(grid[0])
     9         
    10         dp = [[i for i in range(n)] for j in range(m)]
    11         
    12         dp[0][0] = grid[0][0]
    13         
    14         for i in range(1, n):
    15             dp[0][i] = dp[0][i - 1] + grid[0][i]
    16         
    17         for i in range(1, m):
    18             dp[i][0] = dp[i - 1][0] + grid[i][0]
    19         
    20         for i in range(1, m):
    21             for j in range(1, n):
    22                 dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
    23         
    24         return dp[m - 1][n - 1]
  • 相关阅读:
    Linux ps命令
    SecureCRT注册机使用方法
    微信消息的处理和应答
    微信公众号开发--开发服务器接入微信服务器
    RESTful架构
    OAuth2.0详解
    HTTP头详解
    Cookie/Session机制详解
    学习tornado:安全
    python tornado框架实现CRUD
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5093532.html
Copyright © 2011-2022 走看看