62. 不同路径(Medium)
Python示例
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0] * n for _ in range(m)]
# 先把边界条件计算好
for i in range(n):
dp[0][i] = 1
for i in range(m):
dp[i][0] = 1
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]
Go示例
func uniquePaths(m int, n int) int {
dp := make([][]int, m)
for i:= 0; i < m; i++ {
dp[i] = make([]int, n)
}
for i := 0; i < n; i++ {
dp[0][i] = 1
}
for i := 0; i < m; i++ {
dp[i][0] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
}
}
return dp[m - 1][n - 1]
}