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:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
解释
类似一个迷宫问题,从一个地图的左上角移动到右下角每次只能像下或者向上,每个格子中有一个数字,
问如何走才能使得走过的格子中的数字和最小。这是典型的BFS问题和动态规划,从起点开始扩散,
每次向2个方向扩散影响,同一个格子也之受自己左边的值和上方的值影响,所以可以得出状态转移方程:
cost[i][j] = min(cost[i-1][j]/表示上面的格子/, cost[i][j-1]/表示左边的格子/) + val[i][j]
其中cost表示走到每个格子需要的最小和,val表示每个格子中的数字。
AC代码
class Solution {
public int minPathSum(int[][] grid) {
int [][] dp = new int[grid.length][grid[0].length];
dp[0][0] = grid[0][0];
for (int i = 0; i < grid.length; ++i) {
for (int j = 0; j < grid[0].length; ++j) {
if (i == 0&&j==0) continue;
if (i==0&&j>0) dp[i][j] += ( dp[i][j-1] + grid[i][j]);
else if (j==0 && i > 0) dp[i][j] += ( dp[i-1][j] + grid[i][j]);
else dp[i][j] += ( Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j]);
}
}
return dp[grid.length-1][grid[0].length-1];
}
}