LeetCode 0064. Minimum Path Sum Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0064. Minimum Path Sum

Description

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.

 

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

Solutions

Solution 1: Dynamic Programming

We define f[i][j] to represent the minimum path sum from the top left corner to (i, j). Initially, f[0][0] = grid[0][0], and the answer is f[m - 1][n - 1].

Consider f[i][j]:

  • If j = 0, then f[i][j] = f[i - 1][j] + grid[i][j];
  • If i = 0, then f[i][j] = f[i][j - 1] + grid[i][j];
  • If i > 0 and j > 0, then f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j].

Finally, return f[m - 1][n - 1].

The time complexity is O(m × n), and the space complexity is O(m × n). Here, m and n are the number of rows and columns of the grid, respectively.

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) f = [[0] * n for _ in range(m)] f[0][0] = grid[0][0] for i in range(1, m): f[i][0] = f[i - 1][0] + grid[i][0] for j in range(1, n): f[0][j] = f[0][j - 1] + grid[0][j] for i in range(1, m): for j in range(1, n): f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j] return f[-1][-1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !