![]() |
VOOZH | about |
You are standing on a point (n, m) and you want to go to origin (0, 0) by taking steps either left or down i.e. from each point you are allowed to move either in (n-1, m) or (n, m-1). Find the number of paths from point to origin.
Examples:
Input : 3 6 Output : Number of Paths 84 Input : 3 0 Output : Number of Paths 1
As we are restricted to move down and left only we would run a recursive loop for each of the combinations of the
steps that can be taken.
// Recursive function to count number of paths
countPaths(n, m)
{
// If we reach bottom or top left, we are
// have only one way to reach (0, 0)
if (n==0 || m==0)
return 1;
// Else count sum of both ways
return (countPaths(n-1, m) + countPaths(n, m-1));
}
Below is the implementation of the above steps.
Number of Paths 10
Time Complexity: O(min(m,n))
Auxiliary Space: O(min(m,n))
We can use Dynamic Programming as there are overlapping subproblems. We can draw recursion tree to see overlapping problems. For example, in case of countPaths(4, 4), we compute countPaths(3, 3) multiple times.
Number of Paths 10
Time Complexity: O(n*m)
Auxiliary Space: O(n*m)
Another Approach:
Using Pascal's Triangle Approach, we also solve the problem by calculating the value of n+mCn. It can be observed as a pattern when you increase the value of m keeping the value of n constant.
Below is the implementation of the above approach:
Implementation:
Number of Paths: 10
Time Complexity : O((m+n)*n)
Auxiliary Space : O(n)