赞
踩
- class Solution:
- def uniquePaths(self, m: int, n: int) -> int:
- dp = [[1] * n for _ 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]
可以使用一维数组优化空间复杂度
- class Solution:
- def uniquePaths(self, m: int, n: int) -> int:
- dp = [1] * n
- for i in range(1, m):
- for j in range(1, n):
- dp[j] += dp[j-1]
- return dp[-1]
- class Solution:
- def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
- m = len(obstacleGrid)
- n = len(obstacleGrid[0])
- dp = [[0] * n for _ in range(m)]
- for i in range(m):
- if obstacleGrid[i][0] == 0:
- dp[i][0] = 1
- else:
- break
- for j in range(n):
- if obstacleGrid[0][j] == 0:
- dp[0][j] = 1
- else:
- break
- for i in range(1, m):
- for j in range(1, n):
- if obstacleGrid[i][j] == 1:
- dp[i][j] = 0
- else:
- dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
- return dp[-1][-1]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。