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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
如题,首先最先想到的是数学方法,m行n列,一共需要走m+n-2步,其中m-1步是横向移动,所以只要求C(m+n-2,m-1),用递归的方法
class Solution(object):
def jiecheng(self,n):
if n==1 or n==0:
return 1
else:
return self.jiecheng(n-1)*n
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return self.jiecheng(m+n-2)/(self.jiecheng(m-1)*self.jiecheng(n-1))
考虑动态规划,从0,0走到位置i,j有两种方式,一种是到达了i-1,j,另一种是到达了i,j-1.所需步数p[i][j]等于从0,0走到i-1,j的步数加上从0,0走到i,j-1的步数之和即p[i][j]=p[i-1][j]+p[i][j-1]
代码如下:
class Solution:
# @return an integer
def uniquePaths(self, m, n):
aux = [[1 for x in range(n)] for x in range(m)]
for i in range(1, m):
for j in range(1, n):
aux[i][j] = aux[i][j-1]+aux[i-1][j]
return aux[-1][-1]