LeetCode #62 Unique Paths

Problem

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?

Examples

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
1
2
Input: m = 7, n = 3
Output: 28

Solution1

Method: Dynamic Programming

Time Complexity: O(m * n)

Space Complexity: O(m * n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
table = [[0] * m for _ in range(n)]

for row in range(n):
for col in range(m):
if row == 0:
table[0][col] = 1
elif col == 0:
table[row][0] = 1
else:
table[row][col] = table[row-1][col] + table[row][col - 1]

return table[n-1][m-1]

Solution2

Method: Math

Time Complexity: O(log (m + n))

Space Complexity: O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# O(ln(m+n)), O(1)
# Use Library

return math.factorial(m+n-2)/math.factorial(m-1)/math.factorial(n-1)