卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

  • dp[i][j]: minimum path sum until grid[i][j]

  • Java

(Minimum-Path-Sum.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        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 if(i==0 && j!=0)
                    dp[i][j] = dp[i][j-1]+grid[i][j];
                else if(i!=0 && j==0)
                    dp[i][j] = dp[i-1][j]+grid[i][j];
                else
                    dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1])+grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }
}
  • Python
(Minimum-Path-Sum.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        # dp[i][j]: min path until grid[i][j]

        if not grid:
            return 0
        row = len(grid)
        col = len(grid[0])
        ret = [[0]*(col) for i in range(row)]

        for i in range(0,row):
            for j in range(0, col):
                if i == 0 and j == 0:
                    ret[i][j] = grid[i][j]
                elif i == 0:
                    ret[i][j] = ret[i][j-1] + grid[i][j]
                elif j == 0:
                    ret[i][j] = ret[i-1][j] + grid[i][j]
                else:
                    ret[i][j] = min(ret[i-1][j],ret[i][j-1]) + grid[i][j]
        return ret[row-1][col-1]