CodingNodes / 2-D Dynamic Programming / Unique Paths System design Space play · ←→ step · R restart

Problem

A robot stands on the top-left cell of a grid with m rows and n columns. It wants to reach the bottom-right cell. On every move it may step one cell right or one cell down, nothing else.

Return how many different routes lead from the top-left to the bottom-right cell.

Constraints

  • 1 ≤ m, n ≤ 100
  • The answer always fits in a 32-bit signed integer

Examples: pick one to animate

Solutions

TimeO(m·n) SpaceO(m·n)

Time: Every one of the m·n cells is filled once with a single addition.

Space: The table has m rows of n cells.

dp[r][c] is the number of routes to cell (r, c). You can only arrive from above or from the left, so dp[r][c] = dp[r-1][c] + dp[r][c-1]. The top row and left column have one route each.