2020-05-04 64. Minimum Path Sum Medium

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.

Example:

Input:[  [1,3,1],  [1,5,1],  [4,2,1]]Output:7Explanation:Because the path 1→3→1→1→1 minimizes the sum.




class Solution {

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

        if (grid.length == 0) return 0;

        int sum[][] = new int[grid.length][grid[0].length];

        for (int i = 0; i < grid.length; i++) {

            for (int j = 0; j < grid[0].length; j++) {

                if (i != 0 && j != 0) sum[i][j] = grid[i][j] + Math.min(sum[i - 1][j], sum[i][j - 1]);

                else if (i == 0 && j == 0) sum[i][j] = grid[i][j];

                else if (i == 0) sum[i][j] = grid[i][j] + sum[i][j - 1];

                else if (j == 0) sum[i][j] = grid[i][j] + sum[i - 1][j];

            }

        }

        // System.out.println(Arrays.deepToString(sum));

        return sum[grid.length - 1][grid[0].length - 1];

    }

}



(这题看了答案,我的答案排名83%,靠前的跟我看起来差不多,也不知道是哪里有不同)


第二种解法:

与第一种类似,但是只记录一行的dp就行,空间复杂度减少,但是个人感觉这个代码稍微难理解一点:

class Solution {

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

        if (grid.length == 0) return 0;

        int[] dp = new int[grid[0].length];

        for (int  i = 0; i < grid.length; i++) {

            for (int j = 0; j < grid[0].length; j++) {

                if (j == 0) {

                    dp[j] = dp[j] + grid[i][j];

                } else if (i == 0) {

                    dp[j] = dp[j - 1] + grid[i][j];

                } else {

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

                }

            }

        }

        return dp[grid[0].length - 1];

    }

}

你可能感兴趣的:(2020-05-04 64. Minimum Path Sum Medium)