Thursday, 1 August 2019

Suppose there are 'N' stairs, a person wants to reach the top. Person can climb either 1 (or) 2 stairs at a time. Count the number of ways that a person can reach the top.


Suppose there are 'N' stairs, a person wants to reach the top. Person can climb either 1 (or) 2 stairs at a time. Count the number of ways that a person can reach the top.

StairCase.java
package com.sample.probs;

public class StairCase {
 private int noOfWays[];
 private int topStairCaseNumber;
 private int differentWays;

 public StairCase(int noOfWays[], int topStairCaseNumber) {
  this.noOfWays = noOfWays;
  this.topStairCaseNumber = topStairCaseNumber;
  this.differentWays = noOfWays.length;
 }

 public void printNoOfWays() {
  pathsToReachStairCase(0, "");
 }

 private void pathsToReachStairCase(int currentStairCase, String path) {
  if (currentStairCase == topStairCaseNumber) {
   System.out.println(path.substring(0, path.length() - 2));
   return;
  }

  if (currentStairCase > topStairCaseNumber) {
   return;
  }

  for (int i = 0; i < differentWays; i++) {
   pathsToReachStairCase((currentStairCase + noOfWays[i]), path + (currentStairCase + noOfWays[i]) + "=>");
  }

 }

}


Application.java

package com.sample.app;

import com.sample.probs.StairCase;

public class Application {

 public static void main(String args[]) {
  int noOfWays[] = {1, 2};
  int topStairCaseNumber = 5;
  
  StairCase stairCase = new StairCase(noOfWays, topStairCaseNumber);
  stairCase.printNoOfWays();
 }
}


Output
1=>2=>3=>4=>5
1=>2=>3=>5
1=>2=>4=>5
1=>3=>4=>5
1=>3=>5
2=>3=>4=>5
2=>3=>5
2=>4=>5

You may like



No comments:

Post a Comment