[Backtracking/DP]63. Unique Paths II

  • 分类:Backtracking/DP
  • 时间复杂度: O(n*m)

63. Unique Paths II

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).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

image.png

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:


Input:

[

 [0,0,0],

 [0,1,0],

 [0,0,0]

]

Output: 2

Explanation:

There is one obstacle in the middle of the 3x3 grid above.

There are two ways to reach the bottom-right corner:

1\. Right -> Right -> Down -> Down

2\. Down -> Down -> Right -> Right

代码:

记忆化递归方法:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: 'List[List[int]]') -> 'int':
        res=0
        if obstacleGrid==None or len(obstacleGrid)==0 or len(obstacleGrid[0])==0:
            return res
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])
        res=self.paths(m,n,obstacleGrid,{})
        return res
    
    def paths(self,m,n,obstacleGrid,memo):
        if (m,n) in memo:
            return memo[(m,n)]
        else:
            if m<=0 or n<=0 or obstacleGrid[m-1][n-1]==1:
                return 0
            if m==1 and n==1:
                return 1
            memo[(m,n)]=self.paths(m-1,n,obstacleGrid,memo)+self.paths(m,n-1,obstacleGrid,memo)
            return memo[(m,n)]

DP方法:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: 'List[List[int]]') -> 'int':
        res=0
        if obstacleGrid==None or len(obstacleGrid)==0 or len(obstacleGrid[0])==0:
            return res
        
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])
        
        res_matrix=[[0 for i in range(n+1)] for i in range(m+1)]
        res_matrix[1][1]=1
        for i in range(1,m+1):
            for j in range(1,n+1):
                if obstacleGrid[i-1][j-1]==1:
                    res_matrix[i][j]=0
                else:
                    res_matrix[i][j]+=res_matrix[i-1][j]+res_matrix[i][j-1]
        
        return res_matrix[-1][-1]

讨论:

1.一次通过了,美滋滋,感觉这种题型会做了呢!

你可能感兴趣的:([Backtracking/DP]63. Unique Paths II)