|
| 1 | +# [面试题47. 礼物的最大价值](https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof/) |
| 2 | + |
| 3 | +## 题目描述 |
| 4 | +在一个 `m*n` 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物? |
| 5 | + |
| 6 | +**示例 1:** |
| 7 | + |
| 8 | +``` |
| 9 | +输入: |
| 10 | +[ |
| 11 | + [1,3,1], |
| 12 | + [1,5,1], |
| 13 | + [4,2,1] |
| 14 | +] |
| 15 | +输出: 12 |
| 16 | +解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物 |
| 17 | +``` |
| 18 | + |
| 19 | +**提示:** |
| 20 | + |
| 21 | +- `0 < grid.length <= 200` |
| 22 | +- `0 < grid[0].length <= 200` |
| 23 | + |
| 24 | +## 解法 |
| 25 | +### Python3 |
| 26 | +```python |
| 27 | +class Solution: |
| 28 | + def maxValue(self, grid: List[List[int]]) -> int: |
| 29 | + rows, cols = len(grid), len(grid[0]) |
| 30 | + if rows == 0 or cols == 0: |
| 31 | + return 0 |
| 32 | + vals = [[0 for _ in range(cols)] for _ in range(rows)] |
| 33 | + vals[0][0] = grid[0][0] |
| 34 | + for i in range(1, rows): |
| 35 | + vals[i][0] = vals[i - 1][0] + grid[i][0] |
| 36 | + for j in range(1, cols): |
| 37 | + vals[0][j] = vals[0][j - 1] + grid[0][j] |
| 38 | + for i in range(1, rows): |
| 39 | + for j in range(1, cols): |
| 40 | + vals[i][j] = grid[i][j] + max(vals[i - 1][j], vals[i][j - 1]) |
| 41 | + return vals[rows - 1][cols - 1] |
| 42 | + |
| 43 | +``` |
| 44 | + |
| 45 | +### Java |
| 46 | +```java |
| 47 | +class Solution { |
| 48 | + public int maxValue(int[][] grid) { |
| 49 | + int rows = grid.length, cols = grid[0].length; |
| 50 | + int[][] vals = new int[rows][cols]; |
| 51 | + vals[0][0] = grid[0][0]; |
| 52 | + for (int i = 1; i < rows; ++i) { |
| 53 | + vals[i][0] = vals[i - 1][0] + grid[i][0]; |
| 54 | + } |
| 55 | + for (int j = 1; j < cols; ++j) { |
| 56 | + vals[0][j] = vals[0][j - 1] + grid[0][j]; |
| 57 | + } |
| 58 | + for (int i = 1; i < rows; ++i) { |
| 59 | + for (int j = 1; j < cols; ++j) { |
| 60 | + vals[i][j] = grid[i][j] + Math.max(vals[i - 1][j], vals[i][j - 1]); |
| 61 | + } |
| 62 | + } |
| 63 | + return vals[rows - 1][cols - 1]; |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +### ... |
| 69 | +``` |
| 70 | +
|
| 71 | +``` |
0 commit comments