Skip to content

Commit d8db4ee

Browse files
committed
added modified version of Minimum Path Sum
1 parent b5c8c6a commit d8db4ee

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Minimum Path Sum (**MODIFIED**)
2+
3+
[Leetcode Link](https://leetcode.com/problems/minimum-path-sum/)
4+
5+
## Problem:
6+
7+
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.
8+
9+
**modified**: You can move either down or right _or bottom-right (i+1, j+1)_
10+
11+
## Example:
12+
13+
```
14+
Input: grid = [[1,2,3],
15+
[4,8,2],
16+
[1,5,3]]
17+
Output: 8
18+
Explanation: Because the path 1 → 2 → 2 → 3 minimizes the sum.
19+
```
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def minPathSum(grid):
2+
# init dynamic programming table
3+
dp = [[None for _ in grid[0]] for _ in grid]
4+
dp[0][0] = grid[0][0]
5+
for i in range(1, len(dp)):
6+
dp[i][0] = dp[i-1][0] + grid[i][0]
7+
for j in range(1, len(dp[0])):
8+
dp[0][j] = dp[0][j-1] + grid[0][j]
9+
print("initial dp:", dp)
10+
# fill in dp table
11+
for i in range(1, len(dp)):
12+
for j in range(1, len(dp[i])):
13+
minCostSoFar = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
14+
dp[i][j] = minCostSoFar + grid[i][j]
15+
print("after fill-in:", dp)
16+
return dp[-1][-1]
17+
18+
19+
grid = [[1, 2, 3],
20+
[4, 8, 2],
21+
[1, 5, 3]]
22+
print(minPathSum(grid))

0 commit comments

Comments
 (0)