30-Day Leetcoding Challenge Day18

本题简单的动态规划

分三种情况:

1. 第一行元素:grid[i][j] += grid[i][j-1]

2.第一列元素:grid[i][j] += grid[i-1][j]

3.其他元素:grid[i][j] += min(grid[i-1][j], grid[i][j-1])

返回矩阵最后一个元素

JAVA

class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(i == 0 && j != 0){
                    grid[i][j] += grid[i][j-1];
                }
                if(j == 0 && i != 0){
                    grid[i][j] += grid[i-1][j];
                }
                if(i != 0 && j != 0){
                    grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);
                }
            }
        }
        return grid[m-1][n-1];
    }
}

 

Python3

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        for i in range(m):
            for j in range(n):
                if i == 0 and j != 0:
                    grid[i][j] += grid[i][j-1]
                if j == 0 and i != 0:
                    grid[i][j] += grid[i-1][j]
                if i != 0 and j != 0:
                    grid[i][j] += min(grid[i-1][j], grid[i][j-1])
        return grid[-1][-1]

 

posted @ 2020-04-29 15:52  yawenw  阅读(103)  评论(0编辑  收藏  举报