File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
DynamicProgramming/MinPathSum Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments