sagelearnai

Unique Paths

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #62

A robot starts at the top-left cell of an m × n grid and wants to reach the bottom-right cell, moving only right or down. How many distinct paths are there?

Examples

text
m = 3, n = 7  →  28
m = 3, n = 2  →  3
m = 1, n = 1  →  1

Hints

  1. Every path into cell (r, c) comes from above or from the left.
  2. The first row and first column each have exactly one path.
  3. Combinatorics: you make (m−1) downs and (n−1) rights in some order.

Approach

dp[r][c] = dp[r−1][c] + dp[r][c−1], with the first row and column equal to 1. Only the previous row is needed, so use a single array: row[c] += row[c−1]. The closed form C(m+n−2, m−1) is also O(min(m, n)) and worth mentioning.

Complexity

Time: O(m·n). Space: O(n).

Python solution
def uniquePaths(m, n):
    row = [1] * n
    for _ in range(1, m):
        for c in range(1, n):
            row[c] += row[c - 1]
    return row[-1]
JavaScript solution
function uniquePaths(m, n) {
  const row = new Array(n).fill(1);
  for (let r = 1; r < m; r++) for (let c = 1; c < n; c++) row[c] += row[c - 1];
  return row[n - 1];
}