[LeetCode] 64. 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.

Thought process:
  1. Sub-problem: find the minimum sum path from top left to any point.
  2. Formula: f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]
  3. Initialization: for the first row and first column, there is only one path. Initialize first row and first column with the sums.
  4. Answer: f[m - 1][n - 1].

Solution:

 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
26
27
public class Solution {
    public int minPathSum(int[][] grid) {
        int height = grid.length;
        if (height == 0) {
            return 0;
        }
        int width = grid[0].length;
        
        int[][] f = new int[height][width];
        
        f[0][0] = grid[0][0];
        for (int i = 1; i < height; i++) {
            f[i][0] = f[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < width; i++) {
            f[0][i] = f[0][i - 1] + grid[0][i];
        }
        
        for (int i = 1; i < height; i++) {
            for (int j = 1; j < width; j++) {
                f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
            }
        }
        
        return f[height - 1][width - 1];
    }
}
Time complexity: O(mn).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula