[Dynamic Programming-Coordinate Type-Maximum and Minimum Problem] Lintcode 110. Minimum path sum

Lintcode 110. Minimum path sum

Title description: Given an m*n grid containing only non-negative integers, find a path from the upper left corner to the lower right corner that can minimize the sum of the numbers.

  • You can only move one step down or right at the same time

Insert picture description here
It belongs to the problem of the minimum value in coordinate dynamic programming:

class Solution {
    
    
public:
    /**
     * @param grid: a list of lists of integers
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    int minPathSum(vector<vector<int>> &grid) {
    
    
        int m = grid.size(), n = grid[0].size();
        if (0 == m && n == 0) {
    
    
            return 0;
        }

        vector<vector<int> > f(m, vector<int>(n));
        //1. 起点
        f[0][0] = grid[0][0];

        //2. 边界情况
        for (int i = 1; i < m; ++i) {
    
    
            f[i][0] = f[i - 1][0] + grid[i][0];
        }
        for (int j = 1; j < n; ++j) {
    
    
            f[0][j] = f[0][j - 1] + grid[0][j];
        }

        //3. 状态转移
        for (int i = 1; i < m; ++i) {
    
    
            for (int j = 1; j < n; ++j) {
    
    
                f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; 
            }
        }

        //4. 终点
        return f[m - 1][n - 1];
        
    }
};

Guess you like

Origin blog.csdn.net/phdongou/article/details/114158428
Recommended