Leetcode 63 Unique Paths"/>
Leetcode 63 Unique Paths
Leetcode 63 Unique Paths
题目描述
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
来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路解析
题目要求统计到达终点的不同路径数。
易知若达到终点处,所走步数为 m + n − 2 m+n-2 m+n−2,若要保证到达终点数,则需保证只向下走 m − 1 m-1 m−1或只向右走 n − 1 n-1 n−1,得到不同路径数为 C m + n − 2 m − 1 C_{m+n-2}^{m-1} Cm+n−2m−1,代码如下:
from math import factorial
class Solution:def uniquePaths(self, m: int, n: int) -> int:return int(factorial(m+n-2) / (factorial(m-1) * factorial(n-1)))
- 动态规划
更多推荐
Leetcode 63 Unique Paths
发布评论