Description
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?
Constraints:
·1 <= m, n <= 100
·It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
Example
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:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
Submissions
本题采用排列组合的思想,以图中7x3的网格为例,则机器人需要向右走6步,即m-1步。向下走两步,即n-1步。结果即从8种选择动作中,随机选6步或者两步,即为C68或者C28,等于28。因此可初始化分式上下向量为1,分子为m到m+n-2的乘积,分母为1到n-1的乘积。最后返回分式结果即可。
实现代码如下:
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
shang=1
xia=1
for i in range(m,m+n-1):
shang *= i
xia *= (i-m+1)
return shang//xia