Dynamic Programming: 62 Different Path

62. The different paths

Subject description:

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?

 

Problem-solving ideas:

Dynamic three-step plan:

1. The array elements defined meanings; creating a two-dimensional array sig [m] [n]

2. Identify the relationship between the array;

Imagine the following, the machine is Face to people how to get to (i, j) in this position? Since the robot can walk down ⾛ or right ⾛ go, so there are two ⽅ formula arrival;

One is from the (i-1, j) in this step to reach the position ⾛ take ⼀; one is the (i, j - 1) steps down ⼀ reach this position;

Since the step of calculating all possible, it is possible all the way to go ⾛ paths together, the relationship is dp [i] [j] = dp [i-1] [j] + dp [i] [j -1]

3. Find the initial value;

dp [0] [0 ... .n -1] = 1; // corresponds to the uppermost surface ⼀ ⾏ ⾯ row, the machine is left can only have ⾛;
DP [0 .... 1-m] [0] =. 1; // equivalent to the leftmost column column ⾯ face ⼀, who only has ⾛ machine is down.

 

. 1  class Solution {
 2  public :
 . 3      int uniquePaths ( int m, int n-) 
 . 4      {
 . 5          // int SIG [m] [n-]; 
. 6          / *   dynamically create a two-dimensional array, consider the memory is released, or may leak * / 
. 7          int ** = SIG new new  int * [m];
 . 8          for ( int I = 0 ; I <m; I ++ )
 . 9          {
 10              SIG [I] = new new  int [n-];
 . 11          }
 12 is  
13 is         for (int i=0; i<m; i++)
14         {
15             sig[i][0]=1;
16         }
17         for (int i=0; i<n; i++)
18         {
19             sig[0][i]=1;
20         }
21 
22         for (int i=1; i<m; i++)
23             for (int j=1; j<n; j++)
24             {
25                 sig[i][j] = sig[i-1][j] + sig[i][j-1];
26             }
27         return sig[m-1][n-1];
28     }
29 };

 

Guess you like

Origin www.cnblogs.com/Tavi/p/12555885.html