秋招算法备战第39天 | 62.不同路径、63. 不同路径 II

62. 不同路径 - 力扣(LeetCode)

按照动态规划五部曲走,非常清晰

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[0 for _ in range(n)] for _ in range(m)]
        
        for i in range(m):
            dp[i][0] = 1
        for j in range(n):
            dp[0][j] = 1
    
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
        
        return dp[-1][-1]

上面的代码对于数据定义和初始化还能优化,具体如下

def uniquePaths(m, n):
    # 初始化二维数组dp
    dp = [[1] * n for _ in range(m)]
    
    # 遍历每个点计算到达该点的路径数量
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = dp[i-1][j] + dp[i][j-1]
            
    return dp[m-1][n-1]

63. 不同路径 II - 力扣(LeetCode)

和上一题不一样的地方在于初始化以及根据条件不同有不同的状态转移公式

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        dp = [[0]*n for _ in range(m)]

        for i in range(m):
            if obstacleGrid[i][0] == 1:
                break
            dp[i][0] = 1
        for j in range(n):
            if obstacleGrid[0][j] == 1:
                break
            dp[0][j] = 1
    
        for i in range(1, m):
            for j in range(1, n):
                if obstacleGrid[i][j] == 1:
                    continue
                if obstacleGrid[i-1][j] == 0 and obstacleGrid[i][j-1] == 0:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
                elif obstacleGrid[i-1][j] == 1 and obstacleGrid[i][j-1] == 0:
                    dp[i][j] = dp[i][j-1]
                elif obstacleGrid[i-1][j] == 0 and obstacleGrid[i][j-1] == 1:
                    dp[i][j] = dp[i-1][j]
                
        return dp[-1][-1]

后面发现状态转移方程可以简化,在obstacleGrid[i][j] == 0的情况下,不需要再对上左两个方向的障碍物做判断,直接相加即可,因为障碍物点对应的dp值一定为0,代码如下

def uniquePathsWithObstacles(obstacleGrid):
    if not obstacleGrid or obstacleGrid[0][0] == 1:
        return 0
    
    m, n = len(obstacleGrid), len(obstacleGrid[0])
    
    # 初始化dp数组为0
    dp = [[0] * n for _ in range(m)]
    dp[0][0] = 1
    
    # 初始化第一行
    for i in range(1, m):
        dp[i][0] = dp[i-1][0] if obstacleGrid[i][0] == 0 else 0
    
    # 初始化第一列
    for j in range(1, n):
        dp[0][j] = dp[0][j-1] if obstacleGrid[0][j] == 0 else 0
    
    # 遍历每个点计算到达该点的路径数量
    for i in range(1, m):
        for j in range(1, n):
            if obstacleGrid[i][j] == 0:
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
            
    return dp[m-1][n-1]

总结

今天的题目开始能够更加直观地体会到按照动态规划五部曲分析题目的意义

你可能感兴趣的:(算法)