-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Sean Prashad
authored and
Sean Prashad
committed
Sep 2, 2019
1 parent
f1694b3
commit f32c573
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Solution { | ||
public int minPathSum(int[][] grid) { | ||
int height = grid.length, width = grid[0].length; | ||
int[][] memo = new int[height][width]; | ||
|
||
for (int[] row : memo) { | ||
Arrays.fill(row, -1); | ||
} | ||
|
||
return helper(grid, 0, 0, memo); | ||
} | ||
|
||
private int helper(int[][] grid, int row, int col, int[][] memo) { | ||
if (row == grid.length - 1 && col == grid[0].length - 1) { | ||
return grid[row][col]; | ||
} | ||
|
||
if (memo[row][col] != -1) { | ||
return memo[row][col]; | ||
} | ||
|
||
if (row == grid.length - 1) { | ||
return grid[row][col] + helper(grid, row, col + 1, memo); | ||
} | ||
if (col == grid[0].length - 1) { | ||
return grid[row][col] + helper(grid, row + 1, col, memo); | ||
} | ||
|
||
int result = grid[row][col] + Math.min(helper(grid, row + 1, col, memo), helper(grid, row, col + 1, memo)); | ||
memo[row][col] = result; | ||
return result; | ||
} | ||
} |