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]
  • 相关阅读:
    配置gulpfile,添加task任务
    requestAnimationFrame初探
    实现图片的预加载和懒加载
    jquery实现复制到粘贴板
    微信H5页面遇到的一些问题
    js实现日历的简单算法
    handlebars.js的运用与整理
    倒计时插件
    div 模拟<select>事件
    Emacs添加主题插件(Win系统)
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5093532.html
Copyright © 2011-2022 走看看