Given a staircase with N steps, you can go up with 1 or 2 steps each time. Output all possible ways you go from bottom to top.
I'm looking for code review, best practices, optimizations etc. Complexity: O(2n)
public final class StairRoutes {
private StairRoutes() {}
/**
* Given a staircase with N steps, you can go up with 1 or 2 steps each time.
* Output all possible way you go from bottom to top.
*
* @param stepCount The number of steps in the stairway
* @return A list containing all possible routes.
*/
public static List<List<Integer>> stairClimbingRoutes(int stepCount) {
if (stepCount <= 0) throw new IllegalArgumentException("The step count: " + stepCount + " should be positive.");
/* a container containing all the possible routes */
final List<List<Integer>> stairRoutes = new ArrayList<List<Integer>>();
calcAllRoutes(stepCount, new LinkedList<Integer>(), stairRoutes);
return stairRoutes;
}
private static void calcAllRoutes(int stepCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
if (stepCount <= 1) {
populateRoute (stepCount, tempList, stairRoutes);
return;
}
processSteps(stepCount, 1, tempList, stairRoutes);
processSteps(stepCount, 2, tempList, stairRoutes);
}
private static void populateRoute (int numStairs, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
if (numStairs == 0) {
stairRoutes.add(new ArrayList<Integer>(tempList));
return;
}
if (numStairs == 1) {
tempList.add(1);
stairRoutes.add(new ArrayList<Integer>(tempList));
tempList.removeLast();
return;
}
}
private static void processSteps(int numStairs, int hopCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
tempList.add(hopCount);
calcAllRoutes(numStairs - hopCount, tempList, stairRoutes);
tempList.removeLast();
}
public static void main(String[] args) {
List<List<Integer>> stairRoutes = stairClimbingRoutes(5);
for (List<Integer> route : stairRoutes) {
for (Integer stair : route) {
System.out.print(stair + ":");
}
System.out.println();
}
}
}