Unique PathsTotal accepted:36748 Total submissions:112531my submissions QuestionSolution
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?
Above is a 3 x 7 grid. How many possible unique paths is there?
Note: m and N would be is at most 100.
Hide TagsArray Dynamic ProgrammingIdea one: Dynamic planning, f[i][j] = F[i-1][j] + f[i][j-1], and f[i][0] = 0, f[0][j]=0, f[1][1] = 1, time complexity O (m*n), Space complexity O (m*n)
classSolution { Public: intUniquepaths (intMintN) {vector<int> Row (n +1,0); Vector<vector<int> > F (M +1, Row); f[1][1] =1; for(inti =1; I <= m; i + +) { for(intj =1; J <= N; J + +) { if(i = =1&& J = =1) Continue; F[I][J]= f[i-1][J] + f[i][j-1]; } } returnF[m][n]; } };
Idea Two: space complexity can also be optimized, f[][] is changed to f[], optimization, time complexity, Space complexity O (n)
classSolution { Public:#if0intUniquepaths (intMintN) {vector<int> Row (n +1,0); Vector<vector<int> > F (M +1, Row); f[1][1] =1; for(inti =1; I <= m; i + +) { for(intj =1; J <= N; J + +) { if(i = =1&& J = =1) Continue; F[I][J]= f[i-1][J] + f[i][j-1]; } } returnF[m][n]; }#endif intUniquepaths (intMintN) {vector<int> f (n +1,0); f[1] =1; for(inti =1; I <= m; i + +) { for(intj =1; J <= N; J + +) { if(i = =1&& J = =1) Continue; F[J]= F[j] + f[j-1]; } } returnF[n]; }};
[Leetcode] Unique Paths