leetcode 64. Minimum Path Sum-最小路径和|动态规划

原题链接:
64. Minimum Path Sum

【思路】

采用动态规划。动态规划要求利用到上一次的结果,是一种特殊的迭代思想,动态规划的关键是要得到递推关系式。对于本题,从原点到达(i, j)的最小路径等于 :原点到达(i-1, j)最小路径与到达(i, j-1)最小路径中的最小值。即 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1],由于本题在 grid 中修改不影响结果,那么我就直接在上面修改,而不申请 n * m 大小的空间了:

public class Solution {
    public int minPathSum(int[][] grid) {
        for(int i=1; i<grid.length; i++) grid[i][0] += grid[i-1][0];
        for(int j=1; j<grid[0].length; j++) grid[0][j] += grid[0][j-1];
        for (int i=1; i<grid.length; i++) {
            for (int j=1; j<grid[0].length; j++) {
                grid[i][j] = Math.min(grid[i][j-1], grid[i-1][j]) + grid[i][j];
            }
        }
        return grid[grid.length-1][grid[0].length-1];
    }
}

61 / 61
 test cases passed. Runtime: 5 ms  Your runtime beats 26.34% of javasubmissions.

上面的空间复杂度为 O(n*m),这里可以优化为O(n):

public class Solution {
    public int minPathSum(int[][] grid) {
        int[] dp = new int[grid.length];
        dp[0] = grid[0][0];
        for(int i=1; i<grid.length; i++) dp[i] = grid[i][0]+dp[i-1];
        for(int j=1; j<grid[0].length; j++)
            for(int i=0; i<grid.length; i++)
                dp[i] = (i==0 ? dp[i] : Math.min(dp[i], dp[i-1])) + grid[i][j];
        return dp[grid.length-1];
    }
}

61 / 61
 test cases passed. Runtime: 4 ms  Your runtime beats 51.38% of javasubmissions.

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        dp = [0]*len(grid)
        dp[0] = grid[0][0]
        for i in range(1,len(grid)) :
            dp[i] = dp[i-1] + grid[i][0]
        for j in range(1, len(grid[0])) :
            for i in range(len(grid)) :
                dp[i] = min(dp[i], dp[i-1]) + grid[i][j] if i > 0 else dp[i]+grid[i][j]
        return dp[len(grid)-1]

61 / 61
 test cases passed. Runtime: 64 ms  Your runtime beats 86.01% of pythonsubmissions.

    原文作者:动态规划
    原文地址: https://blog.csdn.net/happyaaaaaaaaaaa/article/details/51546526
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞