class Solution: def minPathSum(self, grid) -> int: m=len(grid) n=len(grid[0]) if m==0 or n==0: return 0 if m==1 and n==1: return grid[0][0] for i in range(1,n): grid[0][i]=grid[0][i]+grid[0][i-1] for j in range(1,m): grid[j][0]=grid[j-1][0]+grid[j][0] for i in range(1,n): for j in range(1,m): grid[j][i]=min(grid[j][i]+grid[j-1][i],grid[j][i]+grid[j][i-1]) return grid[m-1][n-1]
执行用时 :196 ms, 在所有 python3 提交中击败了22.46%的用户
内存消耗 :15.4 MB, 在所有 python3 提交中击败了5.12%的用户
——2019.10.14
时隔多日,用java再复习一遍,这道题倒是没啥难的。
public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] dp = new int[m][n]; dp[0][0] = grid[0][0]; for(int j = 1;j<n;j++){ dp[0][j] = dp[0][j-1]+grid[0][j]; } for(int i = 1;i<m;i++){ dp[i][0] = dp[i-1][0] + grid[i][0]; } for(int i = 1;i<m;i++){ for(int j = 1;j<n;j++){ dp[i][j] = Math.min(dp[i-1][j] + grid[i][j],dp[i][j-1] + grid[i][j]); } } return dp[m-1][n-1]; }
——2020.6.27