解法一:组合数
一共有m-1和n-1种向下或向右的走法,用组合数排序
from math import factorial
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return int(factorial(m+n-2)/(factorial(m-1)*factorial(n-1)))
解法二:dp
和爬楼梯问题类似,解法求和,啪的一下就过了
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1 for _ in range(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]
然鹅,很快就发现这个其实并不是很快,因为你其实只需要看上一行,以前的都没用,综上,咱们只需要保存一个数组即可解决问题,代码如下:
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1 for _ in range(n)]
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j-1]
return dp[-1]
经过如下优化,空间复杂度可优化至O(N)