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?
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?
这题有两种解法
1.直接的数学表达式 choose m-1 from m+n-2
class Solution:
# @return an integer
def fac(self,n):
if n==1 or n==0:
return 1
return n*self.fac(n-1)
def uniquePaths(self, m, n):
if m==1 or n==1:
return 1
val1=self.fac(m+n-2)
val2=self.fac(m-1)
val3=self.fac(n-1)
result=val1/(val2*val3)
return result
2.动态规划,每一步都是相邻最近的格子的和。
代码如下
class Solution:
# @return an integer
def uniquePaths(self, m, n):
dp=[[0 for index in range(n)] for index in range(m)]
for row in range(m):
dp[row][0]=1
for col in range(n):
dp[0][col]=1
for row in range(1,m):
for col in range(1,n):
dp[row][col]=dp[row-1][col]+dp[row][col-1]
return dp[m-1][n-1]