Unique Paths

来源:互联网 发布:淘宝在国外的影响力 编辑:程序博客网 时间:2024/06/09 17:22

题目详情:https://leetcode.com/problems/unique-paths/description/

一开始又想到了用递归去模拟过程,但是运行时间超时,突然感觉自己用不好递归,不清楚何时该去用递归,何时不该用递归。
递归解法如下

# -*- coding:utf-8 -*-class Solution(object):    def uniquePaths(self, m, n):        """        :type m: int        :type n: int        :rtype: int        """        self.count=0        self.detectPath(1,1,m,n)        return self.count    def detectPath(self,down,right,m,n):        if down==m and right==n:#如果已经走到了m,n的位置            self.count+=1#将路径数量加1            return        elif down>m or right>n:#如果down大于行数或者right大于列数            return#那么直接返回,因为肯定不能到达m,n位置        self.detectPath(down+1,right,m,n)#向下走        self.detectPath(down,right+1,m,n)#向右走

后来为了减少运行时间,开始思考别的方法。因为机器人只能向下走,向右走,所以在某一位置的路径数量和该位置的上位置和左位置有关,更准确的将是两者之和。然后试了试,发现就真是这样的。代码如下:

# -*- coding:utf-8 -*-class Solution(object):    def uniquePaths(self, m, n):        """        :type m: int        :type n: int        :rtype: int        """        ans=[[1]*n for i in range(m)]#建立存储结构        for row in range(1,m):            for column in range(1,n):                #到row,column的路径数为其上边位置的路径数和左边位置的路径数之和                ans[row][column]=ans[row-1][column]+ans[row][column-1]        return ans[m-1][n-1]#返回到达m,n的路径数量
原创粉丝点击