Problem
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right or diagonally at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
Examples
Example 1:
| |
Solution
This problem is very similar to Unique Paths in Grid 1 - Count all paths moving right or down, just adding the diagonal bit.
Method 1 - Recursion
The recursive approach exhaustively tries all possible moves from each position until it either reaches the bottom-right corner (m-1, n-1) or goes out of bounds.
Code
| |
Complexity
- ⏰ Time complexity:
O(3^(m+n)), because each call can lead to three other calls. - 🧺 Space complexity:
O(n), assuming recursion stack
Method 2 - Top Down DP with Memoization
Top-down DP with memoization enhances the recursive approach by caching the results of subproblems. This prevents re-computation for the same cells multiple times.
Code
| |
Complexity
- ⏰ Time complexity:
O(m*n) - 🧺 Space complexity:
O(m*n)
Method 3 - Bottom up DP
Bottom-up DP constructs the solution iteratively using a table where dp[i][j] represents the number of ways to reach cell (i, j). Each cell in the dp table is filled based on the number of ways to reach the cell to its left, above it, and diagonally top-left.
Code
| |
Complexity
- ⏰ Time complexity:
O(m*n) - 🧺 Space complexity:
O(m*n)