Leetcode 64.最小路径和

方法

方法1:动态规划 O(mn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""

if not grid:
return

r,c=len(grid),len(grid[0])
dp=[[0]*c for _ in range(r)]
dp[0][0]=grid[0][0]

for i in range(1,r):
dp[i][0]=dp[i-1][0]+grid[i][0]
for i in range(1,c):
dp[0][i]=dp[0][i-1]+grid[0][i]
for i in range(1,r):
for j in range(1,c):
dp[i][j]=min(dp[i][j-1],dp[i-1][j])+grid[i][j]
return dp[-1][-1]

仅仅改变grid自身

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""

if not grid:
return

r,c=len(grid),len(grid[0])

for i in range(1,r):
grid[i][0]=grid[i-1][0]+grid[i][0]
for i in range(1,c):
grid[0][i]=grid[0][i-1]+grid[0][i]
for i in range(1,r):
for j in range(1,c):
grid[i][j]=min(grid[i][j-1],grid[i-1][j])+grid[i][j]
return grid[-1][-1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return

r,c=len(grid),len(grid[0])
dp=[[float('inf')]*(c+1) for i in range(r+1)]
dp[0][1],dp[1][0]=0,0

for i in range(1,r+1):
for j in range(1,c+1):
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1]
return dp[-1][-1]

参考资料