The problem requires finding the number of unique paths from the top-left corner to the
bottom-right corner of a grid.
We use a
dynamic programming
to solve this.
We create a
2D array grid
where
grid[i][j]
represents
the number of unique paths to reach cell
(i,
j)
.
For the first row and first column, there is
only one way
to reach any
cell (by moving only right or down).
For other cells, the number of paths is the
sum of paths
from the top
cell and the left cell.
This ensures we build the solution incrementally.
class Solution { public int uniquePaths(int m, int n) { int[][] grid = new int[m][n]; for(int i=0;i<m;i++) grid[i][0] = 1; for(int i=0;i<n;i++) grid[0][i] = 1; for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ grid[i][j] = grid[i-1][j] + grid[i][j-1]; } } return grid[m-1][n-1]; } }
The algorithm iterates through each cell of the grid, resulting in a time complexity of O(m * n), where m and n are the dimensions of the grid.
The algorithm uses a 2D array of size m x n to store intermediate results.