Problem
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
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 (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can solve this whole problem by solving the subproblem, so we can use dynamic programming.
-
We can make a tow dimensional array
dp[row][col]
representing that the total steps reach the coordinate ofrow
andcol
. Anddp[row][col] = dp[row-1][col] + dp[row][col-1]
which means the total steps of reaching the current coordinate is equal to the steps reaching the top row plus the steps reaching the left column. -
The base case is reaching any coordinate of the first row is always 1, and reaching the first column is also always 1.
-
Now we can just find out the value of
dp[row-1][col-1]
.
Solution
1 |
|