Leetcode64 Minimum Path Sum

Posted xuweimdm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode64 Minimum Path Sum相关的知识,希望对你有一定的参考价值。

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.

Solution1

public class Solution 
    public int minPathSum(int[][] grid) 
        int m = grid.length;
        if(m==0) return 0;
        int n = grid[0].length;
        if(n==0) return 0;
        int[][] dp = new int[m][n];
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(i==0&&j==0) dp[i][j] = grid[i][j];
                else dp[i][j] = Math.min(i>0?dp[i-1][j]:Integer.MAX_VALUE, j>0?dp[i][j-1]:Integer.MAX_VALUE) + grid[i][j];
            
        
        return dp[m-1][n-1];        
    

Solution2

  • 滚动数组
public class Solution 
    public int minPathSum(int[][] grid) 
        int m = grid.length;
        if(m==0) return 0;
        int n = grid[0].length;
        if(n==0) return 0;
        int[] dp = new int[n];
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(i==0&&j==0) dp[j] = grid[i][j];
                else dp[j] = Math.min(i>0?dp[j]:Integer.MAX_VALUE, j>0?dp[j-1]:Integer.MAX_VALUE) + grid[i][j];
            
        
        return dp[n-1];    
    

Solution3

  • 假如说可以允许改变原始数组的话,则可以直接利用原始的输入数组作为动态规划的中间状态存储用的数组。
public class Solution 
    public int minPathSum(int[][] grid) 
        int m = grid.length;
        if(m==0) return 0;
        int n = grid[0].length;
        if(n==0) return 0;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(i==0&&j==0) continue;
                else grid[i][j] = Math.min(i>0?grid[i-1][j]:Integer.MAX_VALUE, j>0?grid[i][j-1]:Integer.MAX_VALUE) + grid[i][j];
            
        
        return grid[m-1][n-1];   
    

以上是关于Leetcode64 Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode64 Minimum Path Sum

Leetcode64 Minimum Path Sum

[leetcode-64-Minimum Path Sum]

LeetCode 64. Minimum Path Sum

leetcode 64. Minimum Path Sum

LeetCode64 Minimum Path Sum