代码随想录第39天| 62.不同路径 63.不同路径II

62.不同路径

题目链接:https://leetcode.cn/problems/unique-paths/

根据动规五部曲,可以做出

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[1 for i in range(n)] for j 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

题目链接:https://leetcode.cn/problems/unique-paths-ii/

和上面一题大致相同,但因为有障碍物,初始化时需要动点脑子

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        row = len(obstacleGrid)
        col = len(obstacleGrid[0])

        dp = [[0 for _ in range(col)]for _ in range(row)]
        if obstacleGrid[0][0] == 1:
            dp[0][0] = 0
        else:
            dp[0][0] = 1
        
        if dp[0][0] == 0:
            return 0

        for i in range(col):
            if obstacleGrid[0][i] == 1:
                break
            dp[0][i] = 1
        for i in range(row):
            if obstacleGrid[i][0] == 1:
                break
            dp[i][0] = 1
        
        for i in range(1,row):
            for j in range(1,col):
                if obstacleGrid[i][j] == 0:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
        return dp[row-1][col-1]

今日参赛感想

个人相对于上一次有很大进步,但是这次最后两道题目涉及图,最后一题没做出来。

前三题消耗时间45分钟左右,虽然和别人的差距还是非常大,但写题速度还是有所提升,后续应该缩短练习题目时间,持续给自己压力

你可能感兴趣的:(leetcode,算法,职场和发展)