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 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
就是机器人从左上角走到右下角,每次只能向右或向下走一步,问有多少种走法。
思路:动态规划
很显然,到达右下角的前一步只能是它的上边或者左边那个格子。也就是下面这个图的两个红色方块位置。
到达这两个位置的所有路径个数之和就是最终要求的路径个数。按照这种思路往前推,可以得出达到某个位置的路径数为:
A(i,j) = A(i-1,j)+A(i,j-1) ,这里的(i,j)就是某个位置的坐标位置。
另外处理一下特殊情况,在第一行或者第一列的某一格,肯定只能有一种情况到达该位置。
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
ans=0
res={}
if m==1 or n==1:
ans=1
else:
for i in range(n):
for j in range(m):
if i==0 or j==0:
//第一行或第一列
res[(i,j)]=1
else:
res[(i,j)]=res[(i-1,j)]+res[(i,j-1)]
ans=res[(n-1,m-1)]
return ans
THE END.