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.

最小路径求和的问题,用动态规划来解决。每经过一个点都记录从开始到这个点的最小带权路径。当i = 0 或者j = 0的时候,因为只有一个方向可以走,这时的递推式为grid[i][0] = grid[i - 1][0] + grid[i][0] (j = 0) 和grid[0][j] = grid[0][j - 1] + grid[0][j] ( i = 0)。当i >0 并且j > 0 时,递推式为grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j],每次都取一个和最小的路径。代码如下:
public class Solution {
    public int minPathSum(int[][] grid) {
        if(grid == null || grid.length == 0) return 0;
        int m = grid.length;
        int n = grid[0].length;
        for(int i = 1; i < m; i++)
            grid[i][0] = grid[i - 1][0] + grid[i][0];
        for(int j = 1; j < n; j++)
            grid[0][j] = grid[0][j - 1] + grid[0][j];
        for(int i = 1; i < m; i++)
            for(int j = 1; j < n; j++) {
                grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
            }
        return grid[m - 1][n - 1];
    }
}

你可能感兴趣的:(java,最小路径求和)