Java solution (1ms Recursive and 4ms Iterative)


  • 1
    I
    Recursive:
    public int minPathSum(int[][] grid) {
        int[][] dp = new int[grid.length][grid[0].length];
        return minPathSum(grid, 0, 0, dp);
    }
    
    public int minPathSum(int[][] grid, int i, int j, int[][] dp) {
        if (i == grid.length || j == grid[0].length) {
            return Integer.MAX_VALUE;
        }
        if (i == grid.length - 1 && j == grid[0].length - 1) {
            return grid[i][j];
        }
        if (dp[i][j] != 0) {
            return dp[i][j];
        }
        
        int min = grid[i][j];
        min += Math.min(minPathSum(grid, i, j + 1, dp), minPathSum(grid, i + 1, j, dp));
        dp[i][j] = min;
        return min;
    }
    
    Iterative:
    public int minPathSum(int[][] grid) {
        int[][] dp = new int[grid.length][grid[0].length];
        if (grid.length == 0) {
            return 0;
        }
        dp[0][0] = grid[0][0];
        for (int i = 1; i < grid.length; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int j = 1; j < grid[0].length; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.