Question -
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.
Note: You can only move either down or right at any point in time
I know this is a common question and most of you guys would know the question as well as its dynamic programming. I am trying the recursive code here but I am getting the correct output. what is missing in my recursive code? I don't want the iterative or dynamic programming approach. I am trying to build on my own.
It shows incorrect output.
Example -
1 2
1 1
It gives the output as 2. where as the answer is 3.
Thanks.
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def helper(i,j,grid,dp):
if i >= len(grid) or j >= len(grid[0]):
return 0
print grid[i][j]
return grid[i][j]+min(helper(i+1,j,grid,dp),helper(i,j+1,grid,dp))
dp = [[0] * len(grid[0]) for i in range(len(grid))]
val = helper(0,0,grid,dp)
print dp
return val