leetcode-cn Daily Challenge on July 23th, 2020.
Difficulty : Medium
Related Topics : Array、Dynamic Programming
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: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
same as 62. Unique Paths !
- mine
- Java
-
Dynamic Programming
Runtime: 2 ms, faster than 88.22%, Memory Usage: 42.2 MB, less than 70.01% of Java online submissions
// O(R*C)time O(1)space public int minPathSum(int[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int r = grid.length; int c = grid[0].length; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (i == 0 && j == 0) { continue; } else if (i == 0) { grid[i][j] += grid[i][j - 1]; } else if (j == 0) { grid[i][j] += grid[i - 1][j]; } else { grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); } } } return grid[r - 1][c - 1]; }
-
- Java