day34-dynamic programming-part02-8.5

tasks for today:

1. 62.不同路径

2. 63.不同路径II

3. 343.整数拆分(optional)

4. 96.不同的二叉搜索树(optional)

---------------------------------------------------------------------------------

1. 62.不同路径

following the 5-step format for dynamic programming problem, this practice is quit easy.

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

2. 63.不同路径II

The key to solve this practice is that, if obstacle[0][j] and obstacle[i][0] are presented, it equals ro the circumstance that all the block behind it also have obstacles.

Then all the obstacles within the map will cause a zero in dp.

It is worth noting that, when the obstcles are at the start point or the final point, this will lead to a zero answer whatsoever.

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m = len(obstacleGrid[0])
        n = len(obstacleGrid)
        if obstacleGrid[-1][-1] == 1 or obstacleGrid[0][0] == 1:
            return 0
        dp = [[1] * m for _ in range(n)]
        for i in range(m):
            if obstacleGrid[0][i] == 1:
                for j in range(i + 1, m):
                    obstacleGrid[0][j] = 1
                break

        for i in range(n):
            if obstacleGrid[i][0] == 1:
                for j in range(i + 1, n):
                    obstacleGrid[j][0] = 1
                break
        
        for i in range(1, n):
            for j in range(1, m):
                if obstacleGrid[i-1][j] == 1:
                    left = 0
                else:
                    left = dp[i-1][j]
                
                if obstacleGrid[i][j-1] == 1:
                    right = 0
                else:
                    right = dp[i][j-1]
                
                dp[i][j] = left + right
            
        return dp[-1][-1]
  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值