What is Unique Paths
A robot may only move right or down. The number of paths to cell (i, j) is paths from above plus paths from the left. The first row and first column are all 1 — only one hallway into each of those cells.
Brute force approach
(r, c) walk down or right. The number of paths is binomial, but the recursion tree is still exponential.From each cell the robot goes down or right. Cells are reached by many routes. Memoization stores the path count of each cell.
Keep the grid at most 3 by 3. A 3 by 2 grid has 3 paths.
Memoized approach
dp[j] += dp[j-1] on a rolling row. First row and column stay 1. Time O(mn).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each cell | O(1) |
| Fill grid | O(mn) |
| Space | O(n) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations