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.
The following method uses stack to traverse each path. The result is correct, but time limit exceeded! As long as you get the number of paths, you do not need to traverse each path! A simple method.
class Solution {public: int uniquePaths(int m, int n) { int row=0,col=0,res=0; pair<int,int> rowCol; rowCol = make_pair(row,col); stack<pair<int,int>> stackRowCol; stackRowCol.push(rowCol); while(!stackRowCol.empty()){ pair<int,int> temp = stackRowCol.top(); stackRowCol.pop(); row = temp.first; col = temp.second; if(row==m-1 && col==n-1){ res++; continue;} if(row<m-1) { rowCol = make_pair(row+1,col); stackRowCol.push(rowCol); } if(col<n-1) { rowCol = make_pair(row,col+1); stackRowCol.push(rowCol); } }//end while return res; }};
Use the dynamic planning method (DP) to define a m * n matrix. The value in the matrix indicates the number of paths from the current point to the bottom right corner. Suppose (I, j) the number of paths from point to end is C (I, j ),
C (I, j) = C (I + 1, J) + C (I, j + 1); therefore, O (M * n) can be used) computing results of time complexity and O (M * n) space complexity are as follows:
class Solution {public: int uniquePaths(int m, int n) { int row=m-2,col=n-2,res=0; vector<int> vec0(n,1); vector<vector<int> > vec(m,vec0); for(int i=row;i>=0;i--){ for(int j=col;j>=0;j--){ vec[i][j]=vec[i][j+1]+vec[i+1][j]; } } return vec[0][0]; }};