我的解法:
先遍历第一行和第一列,然后剩下的位置就只要计算是从上面过来的和大还是从左边过来的和更大即可
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
m=len(grid)
n=len(grid[0])
for pointer in range(1,n):
grid[0][pointer]+=grid[0][pointer-1]
for pointer in range(1,m):
grid[pointer][0]+=grid[pointer-1][0]
for row in range(1,m):
for col in range(1,n):
grid[row][col]+=max(grid[row-1][col],grid[row][col-1])
return grid[m-1][n-1]
标准解法:
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[0]*n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = dp[i-1][0] + grid[i][0]
for i in range(1, n):
dp[0][i] = dp[0][i-1] + grid[0][i]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j]
return dp[m-1][n-1]