Java Simple DP Solution


  • 0
    J
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (i == 0 && j == 0) continue;
                int top = (i == 0) ? Integer.MAX_VALUE : dp[i - 1][j];
                int left = (j == 0) ? Integer.MAX_VALUE : dp[i][j - 1];
                dp[i][j] = Math.min(top, left) + grid[i][j];
            }
        }
        return dp[m - 1][n - 1];
    }
    

Log in to reply
 

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