[Learning Dynamic Programming] Minimal Path Sum (9)

Table of contents

How to learn dynamic programming?

1. Topic analysis

2. Algorithm principle

1. Status representation

2. State transition equation

3. Initialization

4. Filling order

5. Return value

3. Code writing

Write at the end:


How to learn dynamic programming?

There is no shortcut to learning an algorithm, let alone learning dynamic programming,

Brush dynamic programming algorithm questions with me, and learn dynamic programming together!

1. Topic analysis

Topic Link: 64. Minimum Path Sum - Leetcode 

This question is not difficult to understand, starting from the upper right corner,

You can only go to the right or down, and calculate the minimum path sum to the lower right corner.

2. Algorithm principle

1. Status representation

dp[ i ][ j ] means the minimum path sum from the starting point to the position [ i, j ].

2. State transition equation

Divide the problem according to the latest step, and there are two cases to the [i, j] position,

One is from above: dp[ i - 1 ][ j ] + g[ i ][ j ]

One is from the left: dp[ i ][ j - 1 ] + g[ i ][ j ]

And what we require is the minimum path sum, so the state transition equation is:

dp[ i ][ j ] = min( dp[ i - 1 ][ j ],dp[ i ][ j - 1 ] ) + g[ i ][ j ]

3. Initialization

The initialization is to prevent out of bounds, so we only need to add the upper line and the left line,

However, the value filled in must ensure that it does not affect the subsequent form filling, so we can initialize the entire table to positive infinity,

Then, in order to ensure that there is no problem with filling out the form for the first time, just initialize the position above the first position to 0.

4. Filling order

top to bottom, left to right

5. Return value

Return the minimum path sum in the lower right corner.

3. Code writing

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
        dp[0][1] = 0;
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
            }
        }
        return dp[m][n];
    }
};

Write at the end:

The above is the content of this article, thank you for reading.

If you feel that you have gained something, you can give the blogger a like .

If there are omissions or mistakes in the content of the article, please private message the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131633531