☰ All problems

57. Unique Paths

A robot stands in the top-left cell of an m × n grid (m rows, n columns). It can only move one cell right or one cell down at a time.

Return the number of distinct routes that take the robot to the bottom-right cell.

Example 1
Input: m = 3, n = 3
Output: 6

Explanation: Every route makes 2 right moves and 2 down moves, and there are 6 ways to order them (RRDD, RDRD, RDDR, DRRD, DRDR, DDRR).

Example 2
Input: m = 2, n = 3
Output: 3

Explanation: RRD, RDR and DRR.

Example 3
Input: m = 1, n = 5
Output: 1

Explanation: With a single row the only route is straight to the right.

Constraints

  • 1 <= m, n <= 100
  • The answer is at most 2 * 10^9

Follow-up: Some cells are now blocked by obstacles. How does the recurrence change?

💡 Hint 1

The only ways into cell (r, c) are from the cell above it and from the cell to its left.

💡 Hint 2

So paths[r][c] = paths[r - 1][c] + paths[r][c - 1], with every cell in the first row and first column equal to 1.

💡 Hint 3

You only need one row of the table at a time. (There is also a closed form: choose which of the m + n - 2 moves are the m - 1 down moves.)

/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
function uniquePaths(m, n) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc