leetcode64. 最小路径和

分四种情况:
两条边界和不在边界的情况,因为是在原数组上修改,所以都等于0时不需要改变

def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if i == j == 0: continue
                elif i == 0:  grid[i][j] = grid[i][j - 1] + grid[i][j]
                elif j == 0:  grid[i][j] = grid[i - 1][j] + grid[i][j]
                else: grid[i][j] = min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j]
        return  grid[i][j]
        

递归实现
还是分为几种情况,用备忘录记住已经计算过的路径长度,出界返回一个大值,到达返回当前格子的大小

def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        n = len(grid[0])
        memo = [[-1]*n for i in range(m)]
        def dp(grid,m,n):
            if m == 0 and n == 0:
                return grid[m][n]
            if m < 0 or n < 0:
                return 0x3f3f3f3f
            if memo[m][n] != -1:
                return memo[m][n]
            memo[m][n] = min(dp(grid,m-1,n),dp(grid,m,n-1)) + grid[m][n]
            return memo[m][n]
        return dp(grid,m-1,n-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值