LeetCode 62. 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?

Example 1:

1
2
3
4
5
6
7
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:

1
2
Input: m = 7, n = 3
Output: 28

Constraints:

  • 1 <= m, n <= 100
  • It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

思路

Math/DP.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if not m or not n:
return 0
return math.factorial(m+n-2)/(math.factorial(n-1) * math.factorial(m-1))


# class Solution(object):
# def uniquePaths(self, m, n):
# """
# :type m: int
# :type n: int
# :rtype: int
# """
# dp = [[0] * n for _ in range(m)]
# for i in range(m):
# dp[i][0] = 1
# for i in range(n):
# dp[0][i] = 1
# for i in range(1, m):
# for j in range(1, n):
# dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
# return dp[m - 1][n - 1]