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.
public
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0;
i < m;
i++) {
dp[i][0] = 1;
}
for (int j = 0;
j < n;
j++) {
dp[0][j] = 1;
}
for (int i = 1;
i < m;
i++) {
for (int 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)?