62. Unique Paths 动态规划

62 Unique Paths

对于目标点path[i][j],前一步只能从paths[i - 1][j]或者是paths[i][j - 1]这两个点到达。而且这中路径之前并没有走过,所以目标就是paths[i][j + 1] + paths[i + 1][j]。

def uniquePaths(self, m, n):  
        paths = [[1] for i in range(m)]  # initialize the 1st column to be 1   

        for i in range(n - 1):           # initialize the 1st row to be 1   
        #paths = [[1]*n for i in range(m)] better initialize method
            paths[0].append(1)   

        for i in range(m - 1):  
            for j in range(n - 1):  
                paths[i + 1].append(paths[i][j + 1] + paths[i + 1][j])  

        return paths[m - 1][n - 1]

给定n、m,在mxn的矩阵中,从(0,0)走到(m-1,n-1)一共有多少种法(只能往下和往右走)
根据题目,要走到最后的点需要向下走n-1次,向右走m-1次,总结起来需要走m+n-2次,在这几次中选出向右走的方式,也就是m-1次。

class Solution:
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        def f(n):
            ret = 1
            for i in range(1, n+1):
                ret *= i
            return ret
        return f(m+n-2)//(f(m-1)*f(n-1))

你可能感兴趣的:(python,leetcode)