First, the topic
The topic is this, given a m*n rectangular square, each time a block, and can only go right and down, the upper left to the lower right corner of the path number.
Extension problem: If you write 0 and 1 in the grid, where 1 represents a barrier, that is, the number of paths cannot be obtained through this square.
Second, analysis
Very obvious dynamic programming problem, the first question is very simple, each arrival of the current number of grid path to reach the left side of the path number plus the number of paths to the top grid, namely:
dp[i][j]= Dp[i][j-1] + dp[i-1][j], it is not difficult to write a program, and I can also use the previous round of calculations to reduce the two-dimensional space to a one-dimensional array.
Class Solution {public: int uniquepaths (int m, int n) { int dp[m][n]; for (int i=0;i<m;i++) { dp[i][0] = 1; } for (int j=0;j<n;j++) { dp[0][j] = 1; } for (int i=1;i<m;i++) {for (int j=1;j<n;j++) { dp[i][j] = Dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1];} ;
However, if there are obstacles, we can not simply add the above and to the left of the value, we need to determine whether the current position is an obstacle, if there is zero.
Class Solution {public: int uniquepathswithobstacles (vector<vector<int> > &obstaclegrid) { int m = Obstaclegrid.size (); if (m<1) return 1; int n = obstaclegrid[0].size (); m = m/n; Vector<int> DP (n);//If you use the following, you must explicitly initialize 0, which is the default initialized int dp[n]; Memset (Dp,0,sizeof (DP)); if (obstaclegrid[0][0] = = 1) return 0; else dp[0] = 1; for (int i=1;i<n&&obstaclegrid[0][i]!= 1;i++) { dp[i] = 1; } for (int i=1;i<m;i++) { if (obstaclegrid[i][0] = = 1) dp[0] = 0; for (int j=1;j<n;j++) { if (obstaclegrid[i][j]! = 1) dp[j] + = dp[j-1]; else dp[j] = 0; } } return dp[n-1];} ;
Class Solution {public: int uniquepathswithobstacles (vector<vector<int> > &obstaclegrid) { int m = Obstaclegrid.size (); int n = obstaclegrid[0].size (); Vector<int> DP (n+1,0); m--; int i = n-1; while (i >= 0 && obstaclegrid[m][i]! = 1) { dp[i] = 1; -----I. } while (m--> 0) {//This circular judgment can be considered in the case of only one row for (i = n-1; I >= 0; i--) { Dp[i] = (obstaclegrid[m][i] = = 1)? 0: DP[I+1] + dp[i]; } } return dp[0];} ;
Leetcode:unique Paths