欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态规划--最小路径和

程序员文章站 2022-03-05 18:24:55
...

题目描述
给定一个由非负整数填充的m x n的二维数组,现在要从二维数组的左上角走到右下角,请找出路径上的所有数字之和最小的路径。
注意:你每次只能向下或向右移动。

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.

class Solution:
    def minPathSum(self , grid ):
        m=len(grid)
        n=len(grid[0])
        # write code here
        res=[[0 for i in range(n)] for i in range(m)]
        
        for i in range(m):
            for j in range(n):
                if i==0:
                    res[0][j]=grid[0][j]+res[0][j-1]
                elif j==0:
                    res[i][0]=grid[i][0]+res[i-1][0]
                else:
                    res[i][j]=grid[i][j]+self.mini(res[i-1][j],res[i][j-1])
        return res[i][j]
    def mini(self,a,b):
        return a if a<b else b
        return a<b and a or b
相关标签: LeeCode刷题记录