Ladder : A person is at level 0 and he has options to take 1 step or 2 steps at a time. To reach level 'n', how many number of ways he has ?
Explanation:
For step 0, number of ways =1
For step 1, number of ways =1
For step 2, number of ways =2
For step 3, number of ways =3
For step 4, number of ways =5
For step 5, number of ways =8
and so on...
For step n, number of ways = number(n-1)+number(n-2), let's see the code below:
package abc;
import java.util.Arrays;
import java.util.Scanner;
public class Ladder {
public static void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.println("Enter the value = ");
int userInput = scanner.nextInt();
int n=userInput ;
int[] total = new int[n];
int forLoopLimit = n-1;
for(int i =2;i<=forLoopLimit;i++) {
total[0] = 1;
total[1] = 1;
// total[2]
= 2;
// total[3]
= 3;
// total[4]
= 5;
total[i] = total[i-1]+total[i-2];
System.out.println("The number of ways for step "+i+" = "+total[i]);
}
if(n==0 || n==1) {
int[] num = {1};
System.out.println("return 1, which is: "+Arrays.toString(num));
}
else {
// int
finalVal = n-1;
int[] num = {total[forLoopLimit]};//last value of i=forLoopLimit
System.out.println("return (n-1)+(n-2), which is: "+total[forLoopLimit]+" OR "+Arrays.toString(num));
}
}
}
Enter the value =
7
The number of ways for step 2 = 2
The number of ways for step 3 = 3
The number of ways for step 4 = 5
The number of ways for step 5 = 8
The number of ways for step 6 = 13
return (i-1)+(i-2), which is: 13 OR [13]
Output 2:
Enter the value =
1
return 1, which is: [1]
No comments:
Post a Comment