Unique paths in a grid (recursion)

Medium TimeO(2^(m+n)) naive; O(m·n) DP SpaceO(m + n) stack

A robot starts in the top-left cell of a grid and may move only right or down, never leaving it. Return how many distinct routes reach the bottom-right — a 3 × 3 grid has 6. A grid one cell wide, or one cell tall, has exactly one path.

Examples

Example 1

Input
m = 3n = 3
Output
6
Every route makes 2 moves right and 2 down, and there are 6 orders to make them in.

Example 2

Input
m = 1n = 5
Output
1
A single row, so the only route is straight along it with no choice anywhere.

The Code

function uniquePaths(m, n) {
  if (m === 1 || n === 1) return 1;
  return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
uniquePaths(3, 3);
Done
Step through uniquePaths(3, 3) call by call