Thursday, May 1, 2014

Program of combinations to climb steps

Problem Statement: Suppose a person is climbing stairs with "n" steps and at a time a person can climb "x"steps. So what are the different permutations of climbing this stairs

Ex: If there are 5 steps in stair and at a time person can climb maximum 3 steps. Then following are the different permutations

11111
1112
1121
113
1211
122
131
2111
212
221
23
311
32

Code:

public class Steps {
   
  public void findStep(int steps, String buf){
  
   if (steps == 0){
    System.out.println(buf);
    return;
   }else{
    if (steps == 1){
     findStep(steps-1, buf + "1");
    }
    if (steps == 2){
     findStep(steps-1, buf + "1");
     findStep(steps-2, buf + "2");
    }
   
    if (steps >= 3){
     findStep(steps-1, buf + "1");
     findStep(steps-2, buf + "2");
     findStep(steps-3, buf + "3");
    }
   
   
   }
 
 }
 
  public static void main(String[] args) {
   String buf = new String();
   Steps s = new Steps();
   s.findStep(5, buf);
  }
}

I'll try to improve this program and generalize it in next posts

No comments:

Post a Comment