leetcode Minimum Path Sum

题目链接

思路:
动态规划
一个点只能由左边点或者上边点到达。这样我们做个比较就好

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

public class Solution {
    public int minPathSum(int[][] grid) {
        int n=grid.length;
        int m=grid[0].length;
        int record[][]=new int [n][m];
        record[0][0]=grid[0][0];
        for(int i=1;i<m;i++)
        {
            record[0][i]=record[0][i-1]+grid[0][i];
        }

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

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



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

你可能感兴趣的:(leetcode Minimum Path Sum)