Problem description:
A robot is located at the top-left corner ofMXNGrid (marked 'start' in the dimo-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 dimo-below ).
How many possible unique paths are there?
Above is a 3x7 grid. How many possible unique paths are there?
Note: MAndNWill be at most 100.
Basic idea:
This question can be taken into consideration. If f [I] [j] is set, it indicates the number of all paths in the lattice from top left to column j of row I. How can we get to f [I] [j? There are two methods:
- Step from (i-1, j) to right
- Step from (I, j-1) to the left
So we can list the equations f [I] [j] = f [i-1] [j] + f [I] [j-1]; initialize (I, 0) and (0, j) is 1, so that the number of methods in the bottom right corner can be obtained iteratively.
Code:
Int uniquePaths (int m, int n) {// c ++ if (m = 1 | n = 1) return 1; int array [m] [n]; // init for (int I = 0; I <n; I ++) array [0] [I] = 1; for (int I = 0; I <m; I ++) array [I] [0] = 1; for (int I = 1; I <m; I ++) for (int j = 1; j <n; j ++) {array [I] [j] = array [i-1] [j] + array [I] [j-1];} return array [S-1] [n-1];}
[Leetcode] Unique Paths