Unique Paths
A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. How many possible unique paths are there?
Constraints:
- 1 <= m, n <= 100
- m and n are integers
Examples:
Input: m = 3, n = 7
Output: 28
Explanation: There are 28 unique paths from the top-left corner to the bottom-right corner of a 3x7 grid.
Solutions
Dynamic Programming
The solution uses dynamic programming to build up a 2D array where each cell represents the number of unique paths to that cell. The final result is the value in the bottom-right cell of the array.
const uniquePaths = function (m, n) {
const dp = Array(m)
.fill()
.map(() => Array(n).fill(1));
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
};
Follow-up:
What if the robot can move in all four directions (up, down, left, right)?