Leetcode Note: Unique Paths
I. Description
A robot is located at the top-left corner of a m n grid (marked 'start' in the dimo-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 dimo-below ).
How many possible unique paths are there?
Above is a 3*7 grid. How many possible unique paths are there? <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + DQo8cD48c3Ryb25nPrb + LiDM4sS/t9bo920.vc3ryb25np1_vcd4ncjxwpszixl + placement/validation/Iz + placement/expires + fill "brush: java;"> k[i][j]=k[i-1][j]+k[i][j-1]
When using dynamic planning, pay attention to the setting of boundary conditions.
The following code uses new to create a one-dimensional array (the array size ism * n
) And use it as a two-dimensional array.i
Line,j
The column element can be expressed:k[i * n + j]
In this way, the advantage of creating a two-dimensional array is that the memory is continuous, but the representation is not intuitive.
Iii. Sample Code
# Include
Using namespace std; class Solution {public: // deep search will time out int uniquePaths (int m, int n) {if (m <= 0 | n <= 0) return 0; if (m = 1 | n = 1) return 1; return uniquePaths (m-1, n) + uniquePaths (m, n-1 );} // dynamic planning int uniquePaths2 (int m, int n) // dynamic planning {int * k = new int [m * n]; // there is only one for (int I = 0; I <m; ++ I) k [I * n] = 1; for (int j = 0; j <n; ++ j) k [j] = 1; for (int I = 1; I <m; ++ I) {for (int j = 1; j <n; ++ j) {k [I * n + j] = k [(I-1) * n + j] + k [I * n + j-1];} int result = k [(m-1) * n + n-1]; delete [] k; return result ;}};
Iv. Summary
In fact, if we only find the number of routes, we can completely turn this problem into a mathematical problem. Assume thatm
Linen
Matrix of columns. The total number of steps required for the robot to move from top left to bottom right ism + n - 2
, Where the number of downward steps ism - 1
So the problem becomesm + n - 2
Operation, selectm – 1
The number of time points to go down. You can use the following formula to calculate the number of options:
If you want to go right, the number of steps isn - 1
The problem can also be explained inm + n - 2
Operation, selectn – 1
The number of time points to the right. The formula is as follows: