Problem
A robot is located at the top-left corner of a m x n grid and trying to reach the bottom-right corner of the grid. The robot can only move either down or right at any point in time. How many possible unique paths are there?
Algorithm
Using dynamic programming to solve:
C
n
k
=
C
n
−
1
k
+
C
n
−
1
k
−
1
C_n^k = C_{n-1}^k + C_{n-1}^{k-1}
Cnk=Cn−1k+Cn−1k−1
Code
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if not n or not m:
return 0
step = [[0] * m for _ in range(n)]
step[0][0] = 1
for i in range(n):
for j in range(m):
if i:
step[i][j] += step[i-1][j]
if j:
step[i][j] += step[i][j-1]
return step[n-1][m-1]