题目
Medium
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
思路一
是一个排列组合题。
def uniquePaths(self, m: int, n: int) -> int:
total = m+n-2
ans = 1
for i in range(n-1):
ans = ans * (total-i)
for i in range(n-1):
ans = ans//(i+1)
return ans
思路二
用递归,m 行 n 列的路线数 = (m-1)行 n 列的路线数 + m 行 (n-1) 列的路线数
import collections
def uniquePaths(self, m: int, n: int) -> int:
paths = collections.defaultdict(lambda:1)
for i in range(2,m+1):
for j in range(2,n+1):
paths[str(i)+","+str(j)] = paths[str(i-1)+","+str(j)] + paths[str(i)+","+str(j-1)]
return paths[str(m)+","+str(n)]