3

This is a pretty classic question, and I've heard Google has used this question in their interviews.

Problem: Make a recursive method that prints all the possible unique ways from the base of a staircase to the top of the staircase with n stairs. You can only take 1-step or 2-steps at a time.

Sample output: If it is a staircase with 3 stairs...

1 1 1

2 1

1 2

If it is a staircase with 4 stairs...

1 1 1 1

1 1 2

1 2 1

2 1 1

2 2

*order of the outputs does not matter

I've seen similar questions posted here but all of them asked for the total number of paths. This recursive method needs to print out all the possible paths. The only restriction here is that you must use recursion somewhere in the method. You can use more than 1 method if you want.

xavier
  • 41
  • 3
  • 1
    This is a very similar post but it asks for the total number of paths. http://stackoverflow.com/questions/12255193/count-number-of-possible-paths-up-ladder – xavier Oct 21 '15 at 04:20

1 Answers1

3

Well, if you have 0 stair left, you've reached the end; if you have 1 more stair, next move can be only of size 1; if you have more stairs ahead, next move may be 1 or 2 stairs, so recursion becomes quite simple:

void makeSteps(List<Integer> prevSteps, int s) {
    if (s == 0) {                        // no more stairs left
        System.out.println(prevSteps);
    } else {                             // 1 or more stairs left
        List<Integer> n1 = new ArrayList<>(prevSteps);
        n1.add(1);
        makeSteps(n1, s - 1);
        if (s > 1) {                     // 2 or more stairs left
            List<Integer> n2 = new ArrayList<>(prevSteps);
            n2.add(2); 
            makeSteps(n2, s - 2);
        }           
    }
}

prevSteps represents previous path, s stores number of stairs left. To print all possible ways for n-step stairs, call:

makeSteps(new ArrayList<>(), n);

Very easily this code can be refactored into more generalized form, where possible step size can be not only 1 or 2, but any number up to maxStep:

void makeSteps(List<Integer> prevSteps, int s, int maxStep) {
    if (s == 0) {                        // no more stairs left
        System.out.println(prevSteps);
    } else {                             // 1 or more stairs left
        for (int step = 1; step <= Math.min(maxStep, s); step++) {
            List<Integer> newSteps = new ArrayList<>(prevSteps);
            newSteps.add(step);
            makeSteps(newSteps, s - step, maxStep);
        }           
    }
}

To receive the same result, call it with the third argument:

makeSteps(new ArrayList<>(), 4, 2);
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
  • 1
    Great! Thank you so much! I forgot that you cannot use any form of loops but this is a great start. I like your thinking. I will work on it. Thanks a lot! – xavier Oct 21 '15 at 17:56