[leetcode]Minimum Path Sum

动态规划。就是要注意第0行和第0列的初始化。

public class Solution {

    public int minPathSum(int[][] grid) {

        // Start typing your Java solution below

        // DO NOT write main() function        

        int m = grid.length;

        if (m == 0) return 0;

        int n = grid[0].length;

        if (n == 0) return 0;

        int[][] mx = new int[m][n];

        

        mx[0][0] = grid[0][0];

                

        for (int i = 1; i < m; i++) {

            mx[i][0] = mx[i-1][0] + grid[i][0];

        }

        

        for (int j = 1; j < n; j++) {

            mx[0][j] = mx[0][j-1] + grid[0][j];

        }

        

        for (int i = 1; i < m; i++) {

            for (int j = 1; j < n; j++) {

                mx[i][j] = Math.min(mx[i-1][j], mx[i][j-1]) + grid[i][j];

            }

        }

        

        return mx[m-1][n-1];

    }   

}

  

你可能感兴趣的:(LeetCode)