剑指 Offer 47. 礼物的最大价值

in with 0 comment

剑指 Offer 47. 礼物的最大价值

在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?

示例 1:

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

  1. 动态规划:
    1. 当 i = 0, j = 0:dp[0][0] = grid[0][0]
    2. 当 i = 0:dp[0][j] += dp[0][j - 1]
    3. 当 j = 0:dp[i][0] += dp[i - 1][0]
    4. 当 i != 0 && j != 0:dp[i][j] += Math.max(dp[i - 1, j], dp[i, j - 1])

代码

解法一

class Solution {
    public int maxValue(int[][] grid) {
        int column = grid.length, row = grid[0].length;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (i == 0 && j == 0) continue;
                else if (i == 0) grid[i][j] += grid[i][j - 1];
                else if (j == 0) grid[i][j] += grid[i - 1][j];
                else grid[i][j] += Math.max(grid[i - 1][j], grid[i][j - 1]);
            }
        }
        return grid[column - 1][row - 1];
    }
}
class Solution {
    public int maxValue(int[][] grid) {
        int column = grid.length, row = grid[0].length;
        for (int j = 1; j < row; j++) grid[0][j] += grid[0][j - 1];
        for (int i = 1; i < column; i++) grid[i][0] += grid[i - 1][0];
        for (int i = 1; i < column; i++)
            for (int j  = 1; j < row; j++)
                grid[i][j] += Math.max(grid[i - 1][j], grid[i][j - 1]);
        return grid[column - 1][row - 1];
    }
}
class Solution {
    public int maxValue(int[][] grid) {
        int column = grid.length, row = grid[0].length;
        int[][] res = new int[column + 1][row + 1];
        for (int i = 1; i <= column; i++) {
            for (int j = 1; j <= row; j++) {
                res[i][j] = Math.max(res[i - 1][j], res[i][j - 1]) + grid[i - 1][j - 1];
            }
        }
        return res[column][row];
    }
}