LeetCode#64. Minimum Path Sum

  • Question: For a matrix of m*n, each element is a non-negative number, seek a path from top left to bottom right, so that the sum of all elements passed by the path is the least.
  • Difficulty: Medium
  • Idea: Dynamically update the matrix in the order from top left to bottom right.
    Dynamic equation 1: grid[i][j] = min(grid[i][j-1], grid[i-1][j]) + grid[i][j]
    Dynamic equation 2: Use a size of A one-bit array of n, storing the elements of each column of the previous row, grid[j] = min(grid[j-1],grid[j]) + grid[i][j] grid[j-1] actually stores is the left element value of the current element.
  • Code:
    Method 1:
public int minPathSum(int[][] grid) {
    int m = grid.length;// row
    int n = grid[0].length; // column
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 && j != 0) {
                grid[i][j] = grid[i][j] + grid[i][j - 1];
            } else if (i != 0 && j == 0) {
                grid[i][j] = grid[i][j] + grid[i - 1][j];
            } else if (i == 0 && j == 0) {
                grid[i][j] = grid[i][j];
            } else {
                grid[i][j] = Math.min(grid[i][j - 1], grid[i - 1][j])
                        + grid[i][j];
            }
        }
    }

    return grid[m - 1][n - 1];
}

Method Two:

public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] result = new int[n];
        result[0] = grid[0][0];
        for(int i = 1; i < n; i++){
            result[i] = result[i-1] + grid[0][i];
        }
        for(int i = 1; i < m; i++){
            result[0] += grid[i][0];
            for(int j = 1; j < n; j++){
                result[j] = Math.min(result[j-1],result[j]) + grid[i][j];
            }
        }
        return result[n-1];
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606773&siteId=291194637