[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.
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] <= 100
最小路径和。
给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给一个二维矩阵,每个格子上都有一个非负整数。请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
这是动态规划的入门题。我参考了这个帖子。如果不理解这个题目,请阅读完参考帖子之后再阅读我的代码。这道题我给出三种代码。
时间O(mn)
空间O(mn)
Java实现 - DP自上而下
1 class Solution { 2 int[][] memo; 3 4 public int minPathSum(int[][] grid) { 5 int m = grid.length; 6 int n = grid[0].length; 7 memo = new int[m][n]; 8 for (int[] row : memo) { 9 Arrays.fill(row, -1); 10 } 11 return dp(grid, m - 1, n - 1); 12 } 13 14 private int dp(int[][] grid, int i, int j) { 15 // base case 16 if (i == 0 && j == 0) { 17 return grid[0][0]; 18 } 19 if (i < 0 || j < 0) { 20 return Integer.MAX_VALUE; 21 } 22 if (memo[i][j] != -1) { 23 return memo[i][j]; 24 } 25 memo[i][j] = Math.min(dp(grid, i - 1, j), dp(grid, i, j - 1)) + grid[i][j]; 26 return memo[i][j]; 27 } 28 } 29 // dp自上而下 30 // Time: O(mn) 31 // Space: O(mn)
时间O(mn)
空间O(mn)
Java实现 - DP自底向上
1 class Solution { 2 public int minPathSum(int[][] grid) { 3 int m = grid.length; 4 int n = grid[0].length; 5 int[][] dp = new int[m][n]; 6 dp[0][0] = grid[0][0]; 7 8 for (int i = 1; i < m; i++) { 9 dp[i][0] = dp[i - 1][0] + grid[i][0]; 10 } 11 for (int j = 1; j < n; j++) { 12 dp[0][j] = dp[0][j - 1] + grid[0][j]; 13 } 14 15 for (int i = 1; i < m; i++) { 16 for (int j = 1; j < n; j++) { 17 dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 18 } 19 } 20 return dp[m - 1][n - 1]; 21 } 22 } 23 // dp自底向上 24 // Time: O(mn) 25 // Space: O(mn)
时间O(mn)
空间O(1)
Java实现 - 无需额外空间的自底向上
1 class Solution { 2 public int minPathSum(int[][] grid) { 3 int m = grid.length; 4 int n = grid[0].length; 5 for (int i = 0; i < m; i++) { 6 for (int j = 0; j < n; j++) { 7 if (i == 0 && j != 0) { 8 grid[i][j] += grid[i][j - 1]; 9 } 10 if (j == 0 && i != 0) { 11 grid[i][j] += grid[i - 1][j]; 12 } 13 if (i != 0 && j != 0) { 14 grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 15 } 16 } 17 } 18 return grid[m - 1][n - 1]; 19 } 20 } 21 // 无需额外空间的自底向上 22 // Time: O(mn) 23 // Space: O(1)
相关题目