当前位置:网站首页>966 minimum path sum

966 minimum path sum

2022-07-06 21:00:00 -Lin Zeyu

The title is as follows

Given a... That contains a nonnegative integer m x n grid grid , Please find a path from the top left corner to the bottom right corner , Make the sum of the numbers on the path the smallest .

explain : You can only move down or right one step at a time .

Example 1:
 Insert picture description here
Input :grid = [[1,3,1],[1,5,1],[4,2,1]]
Output :7
explain : Because the path 1→3→1→1→1 The sum of is the smallest .

Example 2:
Input :grid = [[1,2,3],[4,5,6]]
Output :12

m = = grid.length
n = = grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100

Their thinking

Dynamic programming
 Insert picture description here

Solution code

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

版权声明
本文为[-Lin Zeyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131136340711.html