leetcode: 62. Unique Paths

来源:互联网 发布:mac pdf转word网页版 编辑:程序博客网 时间:2024/06/06 15:39

Q

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

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 (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

Note: m and n will be at most 100.

AC

class Solution(object):    def uniquePaths(self, m, n):        """        :type m: int        :type n: int        :rtype: int        """        import math        return math.factorial(m+n-2)/(math.factorial(m-1)*math.factorial(n-1))# Time:  O(m * n)# Space: O(m + n)class Solution2(object):    # @return an integer    def uniquePaths(self, m, n):        if m < n:            return self.uniquePaths(n, m)        ways = [1] * n        for i in xrange(1, m):            for j in xrange(1, n):                ways[j] += ways[j - 1]        return ways[n - 1]if __name__ == "__main__":    assert Solution().uniquePaths(1, 2) == 1


原创粉丝点击