-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL64.java
More file actions
36 lines (36 loc) · 1.19 KB
/
L64.java
File metadata and controls
36 lines (36 loc) · 1.19 KB
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
27
28
29
30
31
32
33
34
35
36
class Solution64 {
class Solution {
/**
* 64. Minimum Path Sum https://leetcode.com/problems/minimum-path-sum/description/
*
* @param grid
* @return
* @timeComplexity O(m * n)
* @spaceComplexity O(m * n)
*/
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] table = new int[m][n];
int sum = 0;
// For each position in the first row, store the cumulative sum
for (int i = 0; i < n; i++) {
sum += grid[0][i];
table[0][i] = sum;
}
sum = 0;
// For each position in the first column, store the cumulative sum
for (int i = 0; i < m; i++) {
sum += grid[i][0];
table[i][0] = sum;
}
// Choose the best path out of the top and left
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
table[i][j] = grid[i][j] + Math.min(table[i - 1][j], table[i][j - 1]);
}
}
return table[m - 1][n - 1];
}
}
}