Unique Paths 62 - LeetCode
There is an m x n grid. One can only move either down or right at any point in time. One is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
Paths[i][j] = paths[i][j-1] + paths[i-1][j]
int no_of_paths(int width, int height)
{
int i,j;
int* no = new int[width];
for (i=0 ;i< width; i++)
{
no[i] = 1;
cout << "1 "; //just for printing/debugging purpose
}
cout << endl; //just for printing/debugging purpose
for (i=1 ;i< height; i++)
{
cout << no[0] << " "; //just for printing/debugging purpose
for (j=1; j< width; j++)
{
no[j] = no[j]+no[j-1];
cout << no[j] << " "; //just for printing/debugging purpose
}
cout << endl; //just for printing/debugging purpose
}
int res = no[width-1];
delete [] no;
return res;
}
http://joaoff.com/2008/01/20/a-square-grid-path-problem/
Generalization to
(m+nn)=(m+n)!m!×n!
(m+nn)=(m+n)!m!×n! .
Read full article from Unique Paths in 2D grid | PROGRAMMING INTERVIEWS
There is an m x n grid. One can only move either down or right at any point in time. One is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
Paths[i][j] = paths[i][j-1] + paths[i-1][j]
int no_of_paths(int width, int height)
{
int i,j;
int* no = new int[width];
for (i=0 ;i< width; i++)
{
no[i] = 1;
cout << "1 "; //just for printing/debugging purpose
}
cout << endl; //just for printing/debugging purpose
for (i=1 ;i< height; i++)
{
cout << no[0] << " "; //just for printing/debugging purpose
for (j=1; j< width; j++)
{
no[j] = no[j]+no[j-1];
cout << no[j] << " "; //just for printing/debugging purpose
}
cout << endl; //just for printing/debugging purpose
}
int res = no[width-1];
delete [] no;
return res;
}
http://joaoff.com/2008/01/20/a-square-grid-path-problem/
- all the paths have size
2×n (the reason is obvious: you have to go rightn positions and down anothern positions); - since we can only go right or down, we can identify every path by a string of Rs and Ds, where a R means going right and a D means going down; as an example, the paths illustrated in the problem statement are (from left to right and from top to bottom): RRDD, RDRD, RDDR, DRRD, DRDR and DDRR;
- the strings mentioned above must contain the same number of Rs and Ds.
From these three observations, we can transform the problem to the following:
How many different strings of size 2×n , consisting of n Rs and n Ds, are there?
(2nn)=(2n)!n!×n! .
Generalization to m×n grids
The generalization to an m×n grid is also simple. The only difference is that the strings have length m+n . Using the same reasoning as above, the number of paths through an m×n grid is: