64. Minimum Path Sum

64. 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.
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 1 : dp 


      // similar to unique paths 
      // use a 2d array to record the minimum nums to get there 
      // return the number at the bottom right corner 
   
      // fill in the top row and left col 
      // top : row = 0; col from 0 to cache[0].length
      // left : row  from 0 to cache.length , col = 0 



class Solution {
    public int minPathSum(int[][] grid) {
      if(grid.length == 0) return 0;
      int row = grid.length;
      int col = grid[0].length;
      int[][] cache = new int[row][col];
      cache[0][0] = grid[0][0];
      for(int i = 1; i < row; i++){
        cache[i][0] = cache[i - 1][0] + grid[i][0];
      }
      for(int i = 1; i < col; i++){
        cache[0][i] = cache[0][i - 1] + grid[0][i];
      }
      
      for(int i = 1; i < row; i++){
        for(int j = 1; j < col; j++){
          cache[i][j] += Math.min(cache[i - 1][j], cache[i][j - 1]) + grid[i][j];
        }
      }
      return cache[row - 1][col - 1];
    }
}

 

 

https://leetcode.com/problems/minimum-path-sum/solution/

 

Approach 3: Dynamic Programming 1D

Approach 4: Dynamic Programming (Without Extra Space)

posted on 2018-09-20 18:17  猪猪&#128055;  阅读(86)  评论(0)    收藏  举报

导航