Java Program for Count ways to reach the n’th stair
Last Updated :
16 Jun, 2022
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top. Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles
Java
class stairs {
static int fib( int n)
{
if (n <= 1 )
return n;
return fib(n - 1 ) + fib(n - 2 );
}
static int countWays( int s)
{
return fib(s + 1 );
}
public static void main(String args[])
{
int s = 4 ;
System.out.println( "Number of ways = " + countWays(s));
}
}
|
Output:
Number of ways = 5
The time complexity of the above implementation is exponential (golden ratio raised to power n). It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
Java
class stairs {
static int countWaysUtil( int n, int m)
{
if (n <= 1 )
return n;
int res = 0 ;
for ( int i = 1 ; i <= m && i <= n; i++)
res += countWaysUtil(n - i, m);
return res;
}
static int countWays( int s, int m)
{
return countWaysUtil(s + 1 , m);
}
public static void main(String args[])
{
int s = 4 , m = 2 ;
System.out.println( "Number of ways = " + countWays(s, m));
}
}
|
Output:
Number of ways = 5
Java
class GFG {
static int countWaysUtil( int n, int m)
{
int res[] = new int [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 ];
}
static int countWays( int s, int m)
{
return countWaysUtil(s + 1 , m);
}
public static void main(String[] args)
{
int s = 4 , m = 2 ;
System.out.println( "Number of ways = " + countWays(s, m));
}
}
|
Output:
Number of ways = 5
Time Complexity: O(m*n)
Auxiliary Space: O(n)
Please refer complete article on Count ways to reach the n’th stair for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...