day17-2022.11.11
题目信息来源
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm
来源:力扣(LeetCode)
剑指 Offer 47. 礼物的最大价值
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物```
题解
应该是动态规划里的简单题了,状态和转移方程都十分清晰。
d
p
[
i
]
[
j
]
=
{
g
r
i
d
[
i
]
[
j
]
,
i
=
0
,
j
=
0
d
p
[
0
]
[
j
−
1
]
+
g
r
i
d
[
0
]
[
j
]
,
i
=
0
d
p
[
i
−
1
]
[
0
]
+
g
r
i
d
[
i
]
[
0
]
,
j
=
0
g
r
i
d
[
i
]
[
j
]
+
m
a
x
(
d
p
[
i
−
1
]
[
j
]
,
d
p
[
i
]
[
j
−
1
]
)
,
e
l
s
e
dp[i][j]=\left\{ \begin{aligned} &grid[i][j],&i=0,j=0\\ &dp[0][j-1]+grid[0][j],&i=0\\ &dp[i-1][0]+grid[i][0],&j=0\\ &grid[i][j]+max(dp[i-1][j], dp[i][j-1]),&else \end{aligned} \right.
dp[i][j]=⎩⎪⎪⎪⎪⎨⎪⎪⎪⎪⎧grid[i][j],dp[0][j−1]+grid[0][j],dp[i−1][0]+grid[i][0],grid[i][j]+max(dp[i−1][j],dp[i][j−1]),i=0,j=0i=0j=0else
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
n = len(grid[0]) # dp矩阵大小为m*n
m = len(grid)
dp = [[0]*n for _ in range(m)]
dp[0][0] = grid[0][0]
# 先获得第0行和第0列的值
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
for i in range(1, m):
dp[i][0] = dp[i-1][0] + grid[i][0]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = max(dp[i-1][j]+grid[i][j], dp[i][j-1]+grid[i][j])
return dp[-1][-1]