62. Unique Paths
Explanation:
To solve this problem, we can use dynamic programming. We will create a 2D array to store the number of unique paths to reach each cell in the grid. The number of unique paths to reach a cell is the sum of the number of paths to reach the cell above it and the cell to the left of it.
-
Initialize a 2D array
dp
of sizem x n
wheredp[i][j]
represents the number of unique paths to reach cell(i, j)
. -
Initialize the first row and first column of
dp
with 1 since there is only one way to reach any cell in the first row or first column. -
Iterate through the grid starting from
(1, 1)
and updatedp[i][j]
asdp[i-1][j] + dp[i][j-1]
. -
Return
dp[m-1][n-1]
which represents the number of unique paths to reach the bottom-right corner.
- Time complexity: O(m x n) where m is the number of rows and n is the number of columns.
- Space complexity: O(m x n) for the 2D array
dp
.
:
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];
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.