Hey everyone. So I think I understand how this code works. It takes the total number of steps, whatever you set n equal to, and subtracts 1, 2, or 3 as applicable and recurses that process. But I don’t understand where/how the results are stored. It looks like they’re in findStep(n), but I don’t see the final piece of the path that leads to that being the desired output.
The program was written in response to the following problem:
Child can take 1, 2, 3 steps. Total steps he has to take is n. Find no. Of ways he can traverse those steps.
So again, my question is: where is the count of the number of ways stored? I don’t see how it can be in findStep(n) because that keeps changing the whole time according to all the subtractions. But the main method sure makes it seem like it has to be in findStep(n).
// Program to find n-th stair
// using step size 1 or 2 or 3.
import java.util.*;
import java.lang.*;
public class GfG{
// Returns count of ways to reach
// n-th stair using 1 or 2 or 3 steps.
public static int findStep(int n)
{
if (n == 1 || n == 0)
return 1;
else if (n == 2)
return 2;
else
return findStep(n - 3) +
findStep(n - 2) +
findStep(n - 1);
}
// Driver function
public static void main(String argc[]){
int n = 4;
System.out.println(findStep(n));
}
}
/* This code is contributed by Sagar Shukla */