题目描述
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
示例 1:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
题解思路
动态规划
dp[m][n] = max(dp[m-1][n], dp[m][n-1])+nums[m][n]
dp[m][n]:表示到第m行第n列能获得礼物价值最大值。
Python3 代码实现
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
if len(grid) == 0 or len(grid[0]) == 0:
return 0
dp = [[0] * len(grid[0])] * len(grid)
for i in range(len(grid)):
for j in range(len(grid[i])):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
elif j == 0:
dp[i][j] = dp[i - 1][j] + grid[i][j]
elif i == 0:
dp[i][j] = dp[i][j - 1] + grid[i][j]
else:
dp[i][j] = max(dp[i][j-1] + grid[i][j], dp[i-1][j] + grid[i][j])
return dp[-1][-1]
C++代码实现
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
vector<vector<int>> dp(grid.size(), vector<int>(grid[0].size(), -1));
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[i].size();j++){
if(i==0 and j==0)
dp[i][j] = grid[i][j];
else if(i==0)
dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j==0)
dp[i][j] = dp[i-1][j] + grid[i][j];
else
dp[i][j] = maxVal(dp[i][j-1] + grid[i][j], dp[i-1][j] + grid[i][j]);
}
}
return dp[dp.size()-1][dp[0].size()-1];
}
public:
int maxVal(int a, int b){
if(a>b)
return a;
return b;
}
};