Java program to solve Climb Stairs using dynamic programming

Hello Everyone! In this Java tutorial, we are going to discuss the problem of climb stairs using ‘n’ of ways using dynamic programming. We are going to use the recursion method to solve this problem.

How to solve climb stairs using dynamic programming in Java

First, understand what is climb stair problem. In this problem, we have to climb the stair from 0 stairs to nth stair using dynamic programming. In other words, There are n stairs, someone status at the bottom wants to reach the endpoint. The individual can climb both 1 stairs or 2 stairs (or a variable number of jumps)at a time. Count the wide variety of approaches, the person can reach the top. But there are few conditions we have to follow:-

  1. You are given a number of n, representing the wide variety of stairs in a staircase.
  2. You are at the 0th step and are required to climb to the top.
  3. You are given n numbers, where ith detail’s value represents -till how far from the step you could jump to in a single move.
  4. You can of path soar fewer number of steps inside the circulate.
  5. You are required to print the range of different paths thru which you could climb to the top.

Java Code for solving Climb Stairs

import java.util.*;

public class Main 
{
    private static final Scanner mega= new Scanner(System.in);

    public static void main(String[] args) throws Exception 
    {
        System.out.println("Enter the number");
        int n = mega.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = mega.nextInt();
        }
        mega.close();

        int[] dp = new int[n + 1];
        dp[n] = 1;

        for (int i = n - 1; i >= 0; i--) {
            if (arr[i] > 0) {
                for (int j = 1; j <= arr[i] && i + j < dp.length; j++) {
                    dp[i] += dp[i + j];
                }
            }
        }

        System.out.println("Result:- "+dp[0]);
    }

}

We have to show or define the variety of ways to climb the stairs from zero to top.

Now, run this program see the output.

Input

Enter the number:- 10
3
3
0
2
1
2
4
2
0
0

Output

Result:- 5

Now, You can understand how to solve climb stair problem using dynamic programming.

Leave a Reply

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