LeetCode 64. Minimum Path Sum
原题链接在这里:https://leetcode.com/problems/minimum-path-sum/
题目:
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.
题解:
与Unique Paths相似。存储历史信息是走到走到历史点的最小权重路径,更新当前点用上面点和左面点中的小值加上grid中当前点的值。
也相同的第二种降维方法.
Time Complexity: O(m*n). Space: O(n). 一维dp优化.
AC Java:
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 /* 4 //Method 1 5 if(grid == null || grid.length == 0 || grid[0].length == 0){ 6 return 0; 7 } 8 int m = grid.length; 9 int n = grid[0].length; 10 int [][] dp = new int[m][n]; 11 dp[0][0] = grid[0][0]; 12 for(int i = 1; i<m; i++){ 13 dp[i][0] = dp[i-1][0] + grid[i][0]; 14 } 15 for(int j = 1; j<n; j++){ 16 dp[0][j] = dp[0][j-1] + grid[0][j]; 17 } 18 for(int i = 1; i<m; i++){ 19 for(int j = 1; j<n; j++){ 20 dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + grid[i][j]; 21 } 22 } 23 return dp[m-1][n-1]; 24 */ 25 26 //Method 2 27 if(grid == null || grid.length == 0 || grid[0].length == 0){ 28 return 0; 29 } 30 int m = grid.length; 31 int n = grid[0].length; 32 int [] dp = new int[n]; 33 dp[0] = grid[0][0]; 34 for(int j = 1; j<n; j++){ 35 dp[j] = dp[j-1] + grid[0][j]; 36 } 37 for(int i = 1; i<m; i++){ 38 for(int j = 0; j<n; j++){ 39 if(j == 0){ 40 dp[j] += grid[i][j]; 41 }else{ 42 dp[j] = Math.min(dp[j],dp[j-1]) + grid[i][j]; 43 } 44 45 } 46 } 47 return dp[n-1]; 48 } 49 }