Unique Paths

Medium2-D dynamic programming

A robot stands in the top-left cell of a grid with m rows and n columns. Each move takes it one cell right or one cell down.

Return how many different routes take it to the bottom-right cell.

Examples

Example 1
Input:  m = 2, n = 4
Output: 4

The one move down can come in any of the 4 columns.

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

Two moves right and two down, in any order: RRDD, RDRD, RDDR, DRRD, DRDR and DDRR.

Constraints

  • 1 ≤ m, n ≤ 100
  • The answer is at most 2 × 10⁹.

Stuck?

Hint 1

The robot reaches a cell from the cell above it or the cell to its left, so the routes to a cell are the routes to those two added up.

Hint 2

Every cell in the top row and the left column has exactly one route. Fill the grid row by row; one row of counts is enough.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur