Unique Paths Problem
Description
LeetCode Problem 62.
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:
Input: m = 3, n = 7
Output: 28
Example 2:
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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Example 3:
Input: m = 7, n = 3
Output: 28
Example 4:
Input: m = 3, n = 3
Output: 6
Constraints:
- 1 <= m, n <= 100
- It's guaranteed that the answer will be less than or equal to 2 * 10^9.
Solution
Approach: Dynamic Programming with One Row
The robot enters a cell either from the cell above or from the cell to its left, so
paths(row, col) = paths(row - 1, col) + paths(row, col - 1).
Every cell in the first row and in the first column has exactly one path: keep moving right, or keep moving down.
We only ever need the previous row, so one array of length n is enough. Start with paths = [1, 1, ..., 1] for the first row. For each next row, go left to right from column 1 and do paths[col] += paths[col - 1]. Before the update, paths[col] still holds the value of the cell above; paths[col - 1] was already updated, so it is the cell to the left in the current row. paths[0] stays 1, which is the first column.
For m = 3, n = 3 the row goes [1,1,1] → [1,2,3] → [1,3,6], so the answer is 6.
The answer is guaranteed to be at most 2 * 109, and every cell's count is no more than the count at the bottom-right corner, so a 32-bit integer never overflows.
Complexity: O(m · n) time and O(n) space.
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# paths[col] = number of ways to reach column col of the current row.
# Every cell of the first row can only be reached by moving right.
paths = [1] * n
for _ in range(1, m):
for col in range(1, n):
# paths[col] still holds the cell above; paths[col - 1] is the cell to the left.
paths[col] += paths[col - 1]
return paths[n - 1]