leetcode 64. Minimum Path Sum-Minimum Path Sum | python dynamic programming

This question is a simplified version of the minimum path problem

. Students who are introductory to the original problem address may be a little confused when they see this question. First of all, they will think of traversing to find the optimal path for each point. This idea is no problem, but how to achieve it?

Similar to this type of problems are the backpacker problem, network flow optimization and other problems. A typical solution to this type of problem is the use of dynamic programming algorithm. The typical application of dynamic programming algorithm solves the optimization problem of dynamic process divided by time.

Then look at the description of this problem:
>Given an m*n grid containing non-negative integers, find a path from the upper left corner to the lower right corner such that the sum of the numbers on the path is the smallest.
>Description: You can only move down or to the right one step at a time.
> Example:
> Input: [[1,3,1], 1,5,1], [4,2,1]] Output: 7 Explanation: Because the sum of paths 1→3→1→1→1 is the smallest.
-------
The idea of ​​​​this question:

The characteristics of dynamic programming require the use of the previous results, which is a special iterative idea. The key to dynamic programming is to obtain the recurrence relation. For this problem, the minimum path from the origin to (i, j) is equal to the minimum of the minimum path from the origin to (i-1, j) and the minimum path to (i, j-1), that is, dp[i][j ] = Math.min(dp[i-1][j], dp[i][j-1]. And this question can directly modify the parameters in the grid without applying for additional space, which makes the space complexity get Effective use, this kind of practice is often used in actual scenarios.

For the specific process and explanation, please refer to the code.

   class Solution:
        def minPathSum(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            n = len (grid)
            m = len (grid [0])
            for i in range(1,n):
                grid[i][0] = grid[i-1][0] + grid[i][0] #First, you need to find the sum of the paths of the points on the left border
        
            for j in range(1,m):
                grid[0][j] = grid[0][j-1] + grid[0][j] #Find the sum of the paths of each point on the upper boundary
     
            for i in range(1,n):
                for j in range(1,m):
                    grid[i][j] = min(grid[i-1][j] , grid[i][j-1]) + grid[i][j] #According to the boundary, the internal points are introduced step by step the sum of the paths of
  
            return grid[n-1][m-1]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324737836&siteId=291194637