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 is there?
The title means to give you a m*n grid, the number of paths from the upper left to the lower right corner can be easily resolved with DP, pushed to the formula res[i][j] = Res[i-1][j] + res[i][j-1]. It means that the number of paths to a particular point is the sum of the number of paths to the left or the upper side of the point.
The code is as follows:
1 classSolution {2 Public:3 intUniquepaths (intMintN) {4vector<vector<int> > Ans (M, vector<int> (n,0));5 for(inti =0; I < m; ++i)6ans[i][0] =1;7 for(intj =0; J < N; ++j)8ans[0][J] =1;9 Ten for(inti =1; I < m; ++i) { One for(intj =1; J < N; ++j) { AANS[I][J] = ans[i-1][J] + ans[i][j-1]; - } - } the returnAns[m-1][n-1]; - } -};
There is also a way to use DFS to implement, but the number of large is easy to time out, the original meaning of the problem may be DFS, here put the code:
1 classSolution {2 Public:3 intUniquepaths (intMintN) {4Times =0;5Maxhor = m, MaxVer =N;6Dfs0,0);7 returnTimes ;8 }9 voidDfsintHorintver) {Ten if(Hor = = Maxhor-1) && (ver = maxver-1)) Onetimes++; A Else{ - if(Hor +1<maxhor)//Note this is not a while -DFS (hor +1, ver); the if(ver +1<MaxVer) -DFS (Hor, ver +1); - } - } + Private: - intTimes ; + intMaxhor; A intMaxVer; at};
Leetcode oj:unique Paths (unique path)