礼物的最大价值
1.题目描述
在一个m*n的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格,直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计算你最多能拿多少价值的礼物?
2.思路
动态规划:grid(i,j)=grid(i,j)+max(grid(i-1,j),grid(i,j-1))
边界条件:
1.在第0行第0列:grid(i,j) = grid(i,j)
2.在第0行:grid(i,j) = grid(i,j) + grid(i,j-1)
3.在第0列:gird(i,j) = grid(i,j) + gird(i-1,j)
4否则:grid(i,j) = grid(i,j) + max(grid(i-1,j), grid(i,j-1))
3.代码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.empty()){
return 0;
}
for(int i = 0;i < grid.size();++i){
for(int j = 0;j < grid[0].size();++j){
if(i == 0 && j == 0){
grid[i][j] = grid[i][j];
}
else if(i == 0){
grid[i][j] = grid[i][j] + grid[i][j-1];
}
else if(j == 0){
grid[i][j] = grid[i][j] + grid[i-1][j];
}
else{
grid[i][j] = grid[i][j] + max(grid[i-1][j],grid[i][j-1]);
}
}
}
return grid[grid.size()-1][grid[0].size()-1];
}
};
4.复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)