周赛时放弃了,虽然知道是动态规划,但是没有什么思路
拜读大佬解法,获得新思路
尝试着写一下代码。
AC!,如果dp接触不多还是需要多思考一下,理解dp的最优子问题和后无效性条件。
python3
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
dirs = [-1,0,1]
dp = [[[0] * cols for _ in range(cols)] for _ in range(rows)]
# basecase
dp[0][0][-1] = grid[0][0] + grid[0][-1]
for r in range(1,rows): # 行号
for i in range(r+1): # 列号,左边机器人
for j in range(cols-r-1, cols): # 列号,右边机器人
for ii in dirs: # 9种组合可能性
for jj in dirs:
if (i < cols) and (j >= 0) \
and (i + ii >= 0) and (i + ii < cols) \
and (j + jj >= 0) and (j + jj < cols) \
and (i != j):
dp[r][i][j] = max(dp[r-1][i+ii][j+jj] + grid[r][i] + grid[r][j], dp[r][i][j])
result = 0
for i in dp[-1]:
for j in i:
result = max(result, j)
return result