Leetcode oj:unique Paths (unique path)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.