[Backtracking/DP]63. Unique Paths II

  • 分類(lèi):Backtracking/DP
  • 時(shí)間復(fù)雜度: 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.一次通過(guò)了,美滋滋,感覺(jué)這種題型會(huì)做了呢!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容