Please Help me write a method to fullfill thisSolutionThe pe
Please Help me write a method to fullfill this
Solution
The person can reach n’th stair from either (n-1)’th stair or from (n-2)’th stair.
Let the total number of ways to reach n’t stair be ‘ways(n)’.
The value of ‘ways(n)’ can be written as following.
ways(n) = ways(n-1) + ways(n-2)
The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1).
ways(1) = fib(2) = 1
ways(2) = fib(3) = 2
ways(3) = fib(4) = 3
We can write the recurrence as following.
ways(n, 2) = ways(n-1, 2) + ways(n-2, 2) + ... ways(n-3, 2) + ....ways(1, 2)
// Returns number of ways to reach s\'th stair
static int countWaysToJump(int n)
{
return countWaysToJumpUtil(n+1, 2);
}
// A recursive function used by countWays
static int countWaysToJumpUtil(int n, int m)
{
int res[n];
res[0] = 1;
res[1] = 1;
for (int i=2; i<n; i++)
{
res[i] = 0;
for (int j=1; j<=m && j<=i; j++)
res[i] += res[i-j];
}
return res[n-1];
}
