Parcel-delivery app~25 min2s · 256 MBtarget O(R × C) time, O(C) spaceclassic twin: lc-62dp
A parcel-delivery app runs a warehouse robot on an open floor of aisle squares. The floor has rows rows and cols columns, and nothing blocks the robot. The robot starts at the top left square and must reach the bottom right square, where the parcel waits. Each move goes one square right or one square down.
Your team lead asks: "How many different routes can the robot take?"
Write count_paths(rows, cols).
rows rows and cols columns of squares. The robot starts at row 0, column 0 and finishes at the last row, last column.1,000,000,007. A floor of one square has 1 route.Input: rows = 3, cols = 5
Output: 15Let paths[r][c] be the number of routes from the start to the square in row r, column c. A square is reached from the square above it or from the square on its left, so paths[r][c] = paths[r - 1][c] + paths[r][c - 1].
Row 0 and column 0 have one route each, because the robot can only go straight along them. Fill the table row by row, left to right.
| Row | Column 0 | Column 1 | Column 2 | Column 3 | Column 4 |
|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | 1 |
| 1 | 1 | 2 | 3 | 4 | 5 |
| 2 | 1 | 3 | 6 | 10 | 15 |
The last square holds 15, so there are 15 routes.
Input: rows = 1, cols = 6
Output: 1A single row has only one route: right, right, right, right, right.
Input: rows = 3, cols = 3
Output: 6Choose which 2 of the 4 moves go down: 6 routes.
1 ≤ rows ≤ 1,0001 ≤ cols ≤ 1,0001,000,000,007.A floor of 1,000 by 1,000 squares has a million squares. The number of routes is about 10 to the power 600, so no list of routes can be made, and no 64-bit integer can hold the count. A table with one entry for each square costs a million steps, and the modulus keeps every number small.