[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:
- Sub-problem: find the minimum sum path from top left to any point.
- Formula: f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]
- Initialization: for the first row and first column, there is only one path. Initialize first row and first column with the sums.
- 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
Post a Comment