How to Solve Climb Stairs in Java

In this Java tutorial, we are going to discuss the climb stairs using ‘n’ of paths in Java. We are going to use the recursion method to solve this problem.

Solve climb stairs & count ways to reach the nth in Java

First, understand what is climb stair problem, In this problem, we’ve given nth stair we’ve got a start from 0 and go to the nth stair by taking step 1, 2, or three. We will take both 1 step, 2 steps, or 3 steps at a time. In this trouble, we have to be counted how many feasible ways the stairs.

Let’s start,

  1. You are given a number of n, representing the variety of stairs in a staircase..
  2. You are on the 0th step and are required to climb to the top.
  3. In one pass, you’re allowed to climb 1, 2, or three stars.

Java Code for solving Climb Stairs

import java.util.Scanner;

public class Main 
{
    public static int path(int n)
    {
        if(n==0)
        {
            return 1;
        }
        else if(n<0)
        {
            return 0;
        }
        int path1=path(n-1);
        int path2=path(n-2);
        int path3=path(n-3);
        
        int final_path=path1+path2+path3;
        return final_path;
    }

    public static void main(String[] args) throws Exception {
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter the nth:-")
        int nfs = sc.nextInt();
        int result=path(nfs);
        System.out.println("Number of count Paths :-"+result);
    }
}

Step –

  1.  First, we create a new program in python and pass the parameter to function.
  2. Then, we create a recursive function (path(int n)) which takes only one parameter.
  3. Check the base cases. If the value of n is less than 0 then return 0, and else if the value of n is equal to zero then return 1 as it is the starting stair.
  4. Call the function recursively with values n-1, n-2 and n-3 and sum up the values that are lower back, i.e. final_path = path(n-1) + path(n-2) + path(n-3).
  5. Finally, return the value of the final result &  print the total count.

Input

Enter the nth:-
4

Output

Number of count Paths :- 7

Now, You may apprehend the way to count from path zero to nth the use of recursion.

Leave a Reply

Your email address will not be published. Required fields are marked *