62. The different paths

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Q. How many different paths there are in total?

 

 

 For example, the map is a grid of 7 x 3. How many possible paths have?

Example 1:

Input: m = 3 , n-= 2 
Output: 3 
Explanation: 
From top left corner, a total of three paths to reach the bottom right corner.
1 . Right -> Right -> down
 2 . Right -> Down -> Right
 3 down -> right -> right

Example 2:

Input: m = . 7 , n-= . 3 
Output: 28

prompt:

  • 1 <= m, n <= 100
  • Data subject to ensure that the answer is less than equal to 2 * 10 ^ 9

Thinking: feeling suddenly out recursive, recursive formula for F (m, n) = F (m-1, n) + F (m, n-1);

Code:

 1 class Solution {
 2 public:
 3     int uniquePaths(int m, int n) {
 4        //F(m,n) = F(m-1,n)+F(m,n-1);
 5        int a[101][101];
 6        if(m == 0 || n == 0) return 1;
 7        for(int i = 0;i < m; ++i) {
 8            for(int j = 0 ;j < n;++j) {
 9                if(i == 0 || j == 0) {
10                    a[i][j] = 1;
11                } else {
12                    a[i][j] = a[i-1][j] + a[i][j-1];
13                }
14            }
15        }
16        return a[m - 1][n - 1];
17     }
18 };

Postscript: This question should have said at the permutations and combinations in high school, in fact, the result is m + n m step in the selection step right away, so a direct return to C (m, m + n) can be.

 

Guess you like

Origin www.cnblogs.com/Swetchine/p/12664090.html