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;ifor(int j=0;jif(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;ifor(int j=0;jif(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;ifor(int j=0;jif(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];   
    }
}

你可能感兴趣的:(Leetcode)