Professional Documents
Culture Documents
Unique Paths
Unique Paths
Unique Paths
Problem Description :
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]).
The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move
either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take
to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to 2 * 109
Input: m = 3, n = 7
Output: 28
Possibilities:
Here , we have two possibilities to reach the bottom right corner i.e Down and Right.
Step 1:
We have to write down our indexes to the matrix first. we have to move from (0,0) to
(m-1,n-1).
Suppose , we are at (0,0) and given 3 * 3 matrix ,we have 2 possibilities i.e we can go
right or down.
Here , we reached the 3rd index which is not present in our matrix , hence we return 0.
Again we reached the third index . So, again we will return 0 and (1, 2) returns 1.
Base case :
If we reach the last cell of the matrix ,i.e (m-1,n-1) we return 1 as we found a valid path.
The code for the following recursive approach looks like this:
Step 2:
Now , we have to memoize our recursive solution.
If we draw the recursion tree, we will see that there are overlapping subproblems.
Instead of computing the same value again and again, we store the values which are
changing in our memo. Hence,whenever we reach the cell which we already did,there is
no need to compute further.