javarecursionstack-overflowcountingrecursive-backtracking

Recursive solution to counting the number of ways you can go up a staircase


I'm trying to solve the problem of "count ways to reach the nth step in a staircase" with recursion. When given a number of stairs to climb, I have to calculate the number of ways to climb taking either 1 or 2 steps at a time. For example, if there are 4 stairs, we would return 5 since we would have:

  * 1 1 1 1
  * 1 1 2
  * 1 2 1
  * 2 1 1
  * 2 2

My code is currently throwing a stack overflow exception:

 public static int countWaysToClimb(int stairs) {
     return countWaysToClimbHelper(stairs, 0, 0);
 }
 
 public static int countWaysToClimbHelper(int sumNeeded, int currentSum, int possibleCombos) {
     // base - we will reach this base multiple times
     if (sumNeeded == currentSum) {
         possibleCombos++;
         // if we already found a combo, we need to reset the sum
         countWaysToClimbHelper(sumNeeded,0,possibleCombos);  
     }
     
     else if (currentSum > sumNeeded) {
         return 0;
     }
     
     // recurse - add 1 and then add 2
     countWaysToClimbHelper(sumNeeded,currentSum+1,possibleCombos);  
     countWaysToClimbHelper(sumNeeded,currentSum+2,possibleCombos);
     return possibleCombos;             
 }

Thank you!


Solution

  • There are some issues in your code:

    Before moving further, let me recap the basics of recursion.

    Every recursive method should contain two parts:

    So the fixed code might look like that:

    public static int countWaysToClimb(int stairs) {
        return countWaysToClimbHelper(stairs, 0);
    }
    
    public static int countWaysToClimbHelper(int sumNeeded, int currentSum) {
        // base - we will reach this base multiple times
        if (sumNeeded == currentSum) {
            return 1;
        } else if (currentSum > sumNeeded) {
            return 0;
        }
        // recurse - add 1 and then add 2
        int possibleCombos = 0;
        possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 1);
        possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 2);
        return possibleCombos;
    }
    

    Note: