剑指 Offer 47. 礼物的最大价值 - 力扣(LeetCode)
简单dp就可以了:
class Solution { public: int maxValue(vector<vector<int>>& grid) { int m = grid.size(); if(m == 0) return 0; int n = grid[0].size(); vector<vector<int>> dp(m+1, vector<int>(n+1, 0)); for(int i = 1; i <= m; ++i){ for(int j = 1; j <= n; ++j){ dp[i][j] = grid[i-1][j-1] + max(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } };同样可以进行状态压缩,压成两行就是用滚动数组,也可以压缩到一维:
class Solution { public: int maxValue(vector<vector<int>>& grid) { int m = grid.size(); if(m == 0) return 0; int n = grid[0].size(); vector<int> dp(n+1, 0); for(int i = 1; i <= m; ++i){ for(int j = 1; j <= n; ++j){ dp[j] = grid[i-1][j-1] + max(dp[j], dp[j-1]); } } return dp[n]; } };