A robot is located at the top-left corner of an 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?
m
and n
: 1m
and n
: 100This problem can be solved using dynamic programming. We’ll create a 2D DP array where dp[i][j]
represents the number of unique paths to reach cell (i, j)
.
(i, j)
, the number of ways to get there is the sum of the number of ways to get to the cell directly above (dp[i-1][j]
) and the number of ways to get to the cell directly to the left (dp[i][j-1]
).dp[m-1][n-1]
will be our answer.#include <vector>
using namespace std;
class Solution {
public:
int uniquePaths(int m, int n) {
// Initialize the DP table with size m x n filled with 0
vector<vector<int>> dp(m, vector<int>(n, 0));
// Set the first row cells to 1
for(int i = 0; i < n; i++) {
dp[0][i] = 1;
}
// Set the first column cells to 1
for(int i = 0; i < m; i++) {
dp[i][0] = 1;
}
// Fill the rest of the DP table
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];
}
}
// The bottom-right cell contains the number of unique paths
return dp[m-1][n-1];
}
};
The time complexity of this solution is (O(m \times n)) because we need to fill in an m x n
table.
The space complexity of this solution is (O(m \times n)) due to the use of a 2D DP array to keep track of the number of paths to each cell.
This approach ensures that we efficiently calculate the number of unique paths using dynamic programming, considering the constraints provided in the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?