LeetCode-Minimum Path Sum

Title description:

Given a  grid  containing non-negative integers   , please find a path from the upper left corner to the lower right corner so that the sum of the numbers on the path is the smallest.m x ngrid

Note: You can only move one step down or right at a time.

Typical dynamic programming problem

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

        //动态规划
        int m = grid.length;  //行数
        int n = grid[0].length;  //列数
        int[][] dp = new int[m][n];
        //确定边界信息
        dp[0][0]=grid[0][0];
        for(int i=1;i<m;i++){
            dp[i][0]=dp[i-1][0]+grid[i][0];
        }

        for(int j=1;j<n;j++){
            dp[0][j]=dp[0][j-1]+grid[0][j];
        }

        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                dp[i][j]=grid[i][j]+Math.min(dp[i-1][j],dp[i][j-1]);
            }
        }
        return dp[m-1][n-1];
    }
}

 

Guess you like

Origin blog.csdn.net/kidchildcsdn/article/details/114239597