1. 题目

LeetCode62_ 不同路径_动态规划

2. 题解

2.1 解法1 :动态规划

# 62
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i in range(m):
for j in range(n):
if 0 <= i - 1 < m:
dp[i][j] = dp[i][j] + dp[i - 1][j]
if 0 <= j - 1 < n:
dp[i][j] = dp[i][j] + dp[i][j - 1]
return dp[m -1][n -1]


if __name__ == "__main__":
s = Solution()
a = s.uniquePaths(3,7)
print(a)

2.2 解法2: 动态规划

class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# 给边缘化的值赋值为1
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[m - 1][n - 1]

2.3 解法3 :解法2空间复杂度优化

class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# 给边缘化的值赋值为1
dp = [1] * n
for _ in range(1, m):
for j in range(1, n):
dp[j] += dp[j - 1]
return dp[n - 1]