Description: 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. Example: In
Description:
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.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Solution:
这道题和之前的两题思路差不多的,之前我们在格子里存储的是遍历到该格子的可能情况数,现在则存储遍历到该格子最小的和即可,遍历到该格子的最小和为当前格子加上左边与上面较小的那个值。
Code:
public int minPathSum(int[][] grid) { int row = grid.length; int col = grid[0].length; int[][] res = new int[row][col]; for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ if (i == 0 && j == 0){ res[i][j] = grid[i][j]; }else if (i == 0){ res[i][j] = res[i][j-1] + grid[i][j]; }else if (j == 0){ res[i][j] = res[i-1][j] + grid[i][j]; }else{ res[i][j] = Math.min(res[i-1][j] + grid[i][j], res[i][j-1] + grid[i][j]); } } } return res[row-1][col-1]; }
运行情况:
Runtime: 2 ms, faster than 99.04% of Java online submissions for Minimum Path Sum. Memory Usage: 42.9 MB, less than 13.73% of Java online submissions for Minimum Path Sum.好像空间有点太大了,也可以不创建新的二维数组,直接存储于原数组,这样空间复杂度会低很多。