xavier
xavier

Reputation: 41

possible paths to the top of a staircase

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.

Upvotes: 3

Views: 780

Answers (1)

Alex Salauyou
Alex Salauyou

Reputation: 14348

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);

Upvotes: 3

Related Questions