Recursion (TLE)
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
return self.helper(obstacleGrid, len(obstacleGrid)-1, len(obstacleGrid[0])-1)
def helper(self, grid, r, c):
if grid[r][c]==1: return 0
if r==0 and c==0: return 1
if r==0: return self.helper(grid, r, c-1)
if c==0: return self.helper(grid, r-1, c)
return self.helper(grid, r, c-1)+self.helper(grid, r-1, c)
DP + memoization
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
mem = [[None for x in range(n)] for y in range(m)]
return self.helper(obstacleGrid, m-1, n-1, mem)
def helper(self, grid, r, c, mem):
if grid[r][c]==1: return 0
if r==0 and c==0: return 1
if mem[r][c]==None:
if r==0: temp = self.helper(grid, r, c-1, mem)
elif c==0: temp = self.helper(grid, r-1, c, mem)
else: temp = self.helper(grid, r-1, c, mem) + self.helper(grid, r, c-1, mem)
mem[r][c] = temp
return mem[r][c]
DP 2D array
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
mem = [[None for x in range(n)] for y in range(m)]
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]==1:
mem[i][j] = 0
continue
if i==0 and j==0:
mem[i][j] = 1
continue
if i==0: mem[i][j] = mem[i][j-1]
elif j==0: mem[i][j] = mem[i-1][j]
else: mem[i][j] = mem[i][j-1] + mem[i-1][j]
return mem[m-1][n-1]
Attention: start from index=1
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0 for i in range(n+1)] for j in range(m+1)]
dp[0][1] = 1
for i in range(1,m+1):
for j in range(1,n+1):
if not obstacleGrid[i-1][j-1]:
dp[i][j] = dp[i][j-1]+dp[i-1][j]
return dp[m][n]
DP 1D array
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
mem = [None for x in range(n)]
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]==1:
mem[j] = 0
continue
if i==0 and j==0:
mem[j] = 1
continue
if i==0: mem[j] = mem[j-1]
elif j==0: continue
else: mem[j] = mem[j-1] + mem[j]
return mem[n-1]
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
mem = [0 for x in range(n)]
mem[0] = 1
for row in obstacleGrid:
for j in range(n):
if row[j]==1:
mem[j] = 0
elif j>0:
mem[j] += mem[j-1]
return mem[n-1]