慢慢的动态规划的感觉来了,今天连做三道AC。套路也差不多,关键找到状态和状态转移方法,分享一下。
62. Unique Paths(Medium)
题目描述:A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
一个机器人在一个m*n的网格起点,只能向下和向右运动一个点,请问到达右下角有多少种不同的路径。
image.png
思路:
动态规划令 dp[i][j] 为运动到i,j位置有多少种不同的路径,每一个网格的前一步一定是该网格正上或者正左节点,状态转移方程式也由该两网格之和决定:
dp[i][j] = dp[i-1][j] + dp[i][j-1],代码如下所示:
#:type m: int
#:type n: int
#:rtype: int
def uniquePaths(self, m, n):
dp = [[1] * m for _ in range(n)]
for i in range(1, n):
for j in range(1, m):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[n-1][m-1]
63. Unique Paths II(Medium)
题目描述:A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
一个机器人在一个m*n的网格起点,只能向下和向右运动一个点。
Now consider if some obstacles are added to the grids. How many unique paths would there be?
现在在网格里面有一些障碍物,请问到达右下角有多少种不同的路径。
思路:该题与上题的区别在与障碍物,加个判断和初始化即可
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
最终代码如下:
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
def uniquePathsWithObstacles(self, obstacleGrid):
n = len(obstacleGrid)
m = len(obstacleGrid[0])
dp = [[0] * m for _ in range(n)]
for i in range(n):
if obstacleGrid[i][0] == 1:
break
dp[i][0] = 1
for i in range(m):
if obstacleGrid[0][i] == 1:
break
dp[0][i] = 1
for i in range(1, n):
for j in range(1, m):
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[n-1][m-1]
64. Minimum Path Sum(Medium)
问腿描述:Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
同样是上两题的图,给定一个m*n的网格,每个网格里包含一个非负整数,找到一条从左上角到右下的最短路径。
思路:同样DP,每一个网格的路径取最小值,
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
不过这道题不需要初始化直接用给的grid即可。
"""
:type grid: List[List[int]]
:rtype: int
"""
def minPathSum(self, grid):
m = len(grid)
n = len(grid[0])
for i in range(1, n):
grid[0][i] += grid[0][i-1]
for i in range(1, m):
grid[i][0] += grid[i-1][0]
for i in range(1, m):
for j in range(1, n):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[-1][-1]
网友评论