python - 矩阵中唯一路径的数量

标签 python algorithm python-3.x data-structures dynamic-programming

我遇到的问题是:

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/

相关文章:

python - sage中调用函数出错

python - 使用 web.py 作为非阻塞 http 服务器

algorithm - 有人可以对这个 8 皇后算法中的递归进行反混淆吗

algorithm - 计算列表中缺少哪个整数的最佳方法是什么?

python - 打印列表中项目的位置

python - TypeError : cannot unpack non-iterable numpy. float64 对象

python - 是否可以使用 XPath 选择器 (lxml) 抓取 html 数据属性?

python - 我可以使用 configparser 制作字典的字典吗?

python - 如何 "cut off the tail"系列

python - 如何在 python 或 matplotlib 中为非常小的值绘制条形图?