βGrid Unique Paths
Using DFS (very bad time complexity)
int res = 0;
void getWays(int i, int j, int m, int n) {
if(i == m && j == n) {
res++;
return;
}
// right
if(m > i)
getWays(i, j + 1, m, n);
// down
if(n > j)
getWays(i + 1, j, m, n);
}
int Solution::uniquePaths(int A, int B) {
getWays(0, 0, A, B);
return res;
}
Using Combination (Optimal)
For a grid of size .
The robot needs to move right and down.
The robot needs to make a total of moves
So we need to make a string of size 12 that contains R s and Ds
This could be present in any combination.
Here we can place R and D fall in the remaining positions.
So we need to choose β places out of β.
This can be done in β ways.
Last updated