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.
public int minPathSum(int[][] grid) {
问题描述:
这个题目是”Unique Path”那道题的扩充,需要找到所有路径中,包含的元素之和最小的那(几)条路径的和。
所有元素都是非负数。
解法一:
思路:
这个问题考虑使用动态规划。
grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
状态转移方程如上,但是有一行或者一列或者一个元素的情况,所有上述情况要考虑全面。
Code:
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for(int i = 0; i < m; i++){
for(int j = 0;j < n; j++){
if(i == 0 && j != 0){
grid[i][j] = grid[i][j] + grid[i][j - 1];
}
else if(i != 0 && j == 0){
grid[i][j] = grid[i][j] + grid[i - 1][j];
}
else if(i == 0 && j == 0){
grid[i][j] = grid[i][j];
}
else{
grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
}
}
}
return grid[m-1][n-1];
}
}
彩蛋:
很显然,上述代码的空间复杂度可以优化。。