+=
grid each cell = routes from it to the bottom-right · S start · F finish
public int uniquePaths(int m, int n) { int[] row = new int[n]; Arrays.fill(row, 1); // bottom row for (int i = 0; i < m - 1; i++) { int[] newRow = new int[n]; Arrays.fill(newRow, 1); // right column for (int j = n - 2; j >= 0; j--) { newRow[j] = newRow[j + 1] + row[j]; } row = newRow; } return row[0];}
- i
- —
- j
- —
- row
- —
- newRow
- —
Why it works
- Brute force walks every route: recurse right and down from the start. Every route is m+n−2 moves, so the tree has about 2m+n leaves.
- Routes add up. The first move from a cell is either right or down, and the two choices never share a route. So routes from a cell = routes from its right neighbour + routes from the cell below.
- One row is enough. A cell only reads the row below and the cell to its right, so the code keeps the row below (
row) and builds the next one (newRow) right to left. O(m·n) time, O(n) space. - Pitfall: the bottom row and the right column are all 1, not 0. From there the robot has exactly one route: straight along the edge.
- Closed form: a route is m−1 downs and n−1 rights in some order, so the answer is C(m+n−2, m−1). Follow-up, Unique Paths II (63): an obstacle cell holds 0 routes, and the same sum works around it.