Sword Finger Offer 47. The Maximum Value of Gifts (C++) Dynamic Programming

A gift is placed on each square of an m*n chessboard, and each gift has a certain value (value greater than 0). You can start from the upper left corner of the board to get the gifts in the grid, and move to the right or down one square at a time until you reach the lower right corner of the board. Given the value of a chessboard and the gifts on it, please calculate the maximum value of gifts you can get?

Example 1:

输入: 
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 12

Explanation: Path 1→3→5→2→1 can get the most valuable gift

提示:
0 < grid.length <= 200
0 < grid[0].length <= 200

Problem-solving ideas:

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

class Solution {
    
    
public:
    int maxValue(vector<vector<int>>& grid) {
    
    
        int m = grid.size(), n = grid[0].size();//m 、n分别表示行列
        for(int j = 1; j < n; j++) // 初始化第一行
            grid[0][j] += grid[0][j - 1];
        for(int i = 1; i < m; i++) // 初始化第一列
            grid[i][0] += grid[i - 1][0];
        for(int i = 1; i < m; i++)
            for(int j = 1; j < n; j++) 
                grid[i][j] += max(grid[i][j - 1], grid[i - 1][j]);
        return grid[m - 1][n - 1];
    }
};

Complexity analysis:

Time complexity O(MN): M and N are matrix row height and column width respectively; dynamic programming needs to traverse the entire grid matrix, using O(MN) time.
Space complexity O(1): In-situ modification uses a constant size of extra space.

Author: jyd
link: https: //leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof/solution/mian-shi-ti-47-li-wu-de-zui -da-jie-zhi-dong-tai-gu/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114981828