p64

LeetCode p64 Minimum Path Sum 题解

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.

题意:

从一个矩阵的左上走到右下,找到那和最小的路线的值。

2.解题思路:

见代码,用dfs超时了TUT,以下借鉴了别人的算法思路。。感觉简洁多了。

3.代码


[title] [] [url] [link text]
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
 
public class Solution {
public int minPathSum(int[][] grid) {
if (grid.length == 0)
return 0;
int n = grid.length;
int m = grid[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0) {
grid[i][j] = grid[i][j];
} 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] + grid[i][j - 1];
} else {
grid[i][j] = grid[i][j]
+ Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
}

return grid[n - 1][m - 1];
}
}


4.一些总结:leetcode 100斩 然而还是个渣渣