Fork me on GitHub

leetcode——[064]Minimum Path Sum最短路径和

题目

给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

示例:

1
2
3
4
5
6
7
8
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

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
2
3
4
5
6
7
8
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

解题方法

简单动态规划问题,状态转移方程为res[i][j] = min(res[i-1][j], res[i][j-1]) + grid[i][j],其中res保存到达每个格子的最短路径和,grid保存每个格子的值,到grid[i][j]的最短路径和为到其左边或上边的最短路径和中的最小值加grid[i][j]。这段代码跑了5ms,超过了93.86%的Java提交。

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
public class Solution {
// Method 1 5ms 93.86%
public int minPathSum(int[][] grid) {
int m = grid.length;
int x = grid[0].length;
int[][] res = new int[m][x];
for (int i = 0; i < m; i++) {
for (int j = 0; j < x; j++) {
if (i == 0 && j == 0) {
res[i][j] = grid[i][j];
}
else if (i == 0) {
res[i][j] = res[i][j-1] + grid[i][j];
}
else if (j == 0) {
res[i][j] = res[i-1][j] + grid[i][j];
}
else{
res[i][j] = Math.min(res[i-1][j], res[i][j-1]) + grid[i][j];
}
}
}
return res[m-1][x-1];
}
}
BJTU-HXS wechat
海内存知己,天涯若比邻。