我遇到的问题是:
A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. How many possible unique paths are there?
我提交的代码是:
class Solution(object):
def uniquePaths(self,m,n):
# m : (int) rows
# n : (int) cols
mat = [[0] * n] * m
for i in range(n):
mat[0][i] = 1
for i in range(m):
mat[i][0] = 1
for i in range(1,m):
for j in range(1,n):
mat[i][j] = mat[i - 1][j] + mat[i][j - 1]
return mat[m - 1][n - 1]
提交后,我发现我的代码仅比其他提交的代码快 21%。这意味着我的代码不是最优的。因此出于好奇,我检查了其他提交,它比我的速度快得多。
更好的解决方案是:
class Solution(object):
def uniquePaths(self, m, n):
p = 1
for i in xrange(n,m+n-1):
p *= i
return p/self.factorial(m-1)
def factorial(self,n):
if n == 0:
return 1
return n*self.factorial(n-1)
正如你所看到的,它的时间复杂度是线性的,而我的时间复杂度是二次的。但我无法理解其背后的逻辑。
最佳答案
您不需要为此使用计算机程序。这是一个简单的组合问题。想象一下 m 个向右箭头和 n 个向下箭头。提出这个问题的另一种方式是我们可以用多少种方式来排列这些箭头?我们可以从 m+n 中选择 m 个点作为右箭头。所以答案是二项式(m, m + n)
关于python - 矩阵中唯一路径的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116512/