Unique Paths
Unique Paths is a medium 2-D Dynamic Programming problem from the Blind 75. The key pattern is 2-d dynamic programming, and a good solution runs in O(m · n) time.
Problem
Count paths from the top-left to bottom-right of an m by n grid using only right and down moves.
Examples
Example 1
Input
{"m":3,"n":4}Output
10Example 2
Input
{"m":4,"n":5}Output
35Example 3
Input
{"m":2,"n":2}Output
2Approach
Each cell's path count is the count from above plus the count from the left; one rolling row is enough. A binomial coefficient also works.
| Pattern | 2-D dynamic programming |
|---|---|
| Time | O(m · n) |
| Space | O(n) |
Watch out for
The first row and first column each have exactly one path.