[LeetCode] Sword refers to Offer 47. The maximum value of gifts (medium) Dynamic programming

There is a gift in 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?

示例 1:

输入: 
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 12
解释: 路径 13521 可以拿到最多价值的礼物
提示:

0 < grid.length <= 200
0 < grid[0].length <= 200

Code:

State transition equation: the upper val and the left val take the larger value + itself

dp[i][j]=max(dp[i-1][j],dp[i][j-1])+grid[i][j];
class Solution {
    
    
public:
    int maxValue(vector<vector<int>>& grid) {
    
    
        int dp[220][220]={
    
    grid[0][0]},len1=grid.size(),len2=grid[0].size();

        for(int i=1;i<len1;i++)  //边界:第一列
            dp[i][0]=dp[i-1][0]+grid[i][0];

        for(int i=1;i<len2;i++)  //边界:第一行
            dp[0][i]=dp[0][i-1]+grid[0][i];

        for(int i=1;i<len1;i++)
            for(int j=1;j<len2;j++)
                dp[i][j]=max(dp[i-1][j],dp[i][j-1])+grid[i][j];

        return dp[len1-1][len2-1]; //右下角的dp
    }
};

Code (rolling array):

class Solution {
    
    
public:
    int maxValue(vector<vector<int>>& grid) {
    
    
        int dp[220]={
    
    grid[0][0]},len1=grid.size(),len2=grid[0].size();

        for(int i=1;i<len2;i++) //第一行
            dp[i]=dp[i-1]+grid[0][i];

        for(int i=1;i<len1;i++)
        {
    
    
            dp[0]=dp[0]+grid[i][0]; //每行第一个特殊处理:上边+自身
            for(int j=1;j<len2;j++)
                dp[j]=max(dp[j],dp[j-1])+grid[i][j];
        }

        return dp[len2-1]; //返回右下角dp
    }
};

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/108466853