Monday, February 2, 2015

Minimum Path Sum LeetCode

First, I try to use the m by n matrix to store the minimum distance to the top-left corner.
Second, we optimize the space from m*n to n. We only store the minimum distance for the current row.


public int minPathSum(int[][] grid) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
       int m = grid.length;
       int n= grid[0].length;
     
       int[] G = new int[n];
     
       for (int i=0; i<m; i++) {
           for (int j=0; j<n; j++) {
               if (j==0) {
                   G[j] += grid[i][j];
               } else if (i==0) {
                   G[j] = G[j-1] + grid[i][j];
               } else {
                   G[j] = Math.min(G[j-1], G[j]) + grid[i][j];
               }
           }
       }
       return G[n-1];
    }

No comments:

Post a Comment