Dynamic Programming 02
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(order does matter)
Problem link :- click here
Code
import java.util.Scanner;
// COUNT WAYS TO REACH THE N'TH STAIR
public class DynamicProgramming_02
{
static int numberOfWaysToReachNthStair(int n, int arr[])
{
if(n==1)
{
arr[1] = 1;
return 1;
}
if(n==2)
{
arr[2] = 2;
return 2;
}
else
{
int ans = numberOfWaysToReachNthStair(n-1, arr) + numberOfWaysToReachNthStair(n-2, arr);
arr[n] = ans;
return ans;
}
}
static int numberOfWaysToReachNthStair2(int n)
{
int arr[] = new int[n+1];
arr[1] = 1;
arr[2] = 2;
for(int i=3; i<=n; i++)
arr[i] = arr[i-1] + arr[i-2];
return arr[n];
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of stairs: ");
int k = s.nextInt();
int arr[] = new int[k+1];
System.out.println(numberOfWaysToReachNthStair(k, arr));
s.close();
}
}
Comments
Post a Comment