递归栈很酷 但超时
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m==1 or n==1:
return 1
return self.uniquePaths(m-1,n)+self.uniquePaths(m,n-1)
逐行dp
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp=[1]*n
for j in range(1,m):
for i in range(1,n):
dp[i]+=dp[i-1]
return dp[n-1]
j从0开始 每个都要判断
python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if obstacleGrid[0][0]==1:return 0
dp=[0]*len(obstacleGrid[0])
for j in range(len(dp)):
if obstacleGrid[0][j]:dp[j]=0
elif j==0:dp[j]=1
else:dp[j]=dp[j-1]
for i in range(1,len(obstacleGrid)):
for j in range(0,len(dp)):
if obstacleGrid[i][j]==1:
dp[j]=0
elif j!=0:
dp[j]+=dp[j-1]
return dp[-1]