Problem statement : A Child is climbing up n steps with either 1 , 2, 3 hops ..how many ways can the child climb up the stairs?
source: cracking the coding interview book.
I have two solutions the brute force and the memoized one.
Wanted to know how to improve my solution further, any issues you see with this code?
description of the code: Brute force: basically count in a recursive manner, as there are 3 ways to reach the nth step so we count number of ways to reach each of n-1 , n-2 and n-3 steps and then sum them up to find the number of ways of reaching the nth step.
memoized solution:
we are now caching the solutions in a hashmap to reuse the solutions.
The Code:
public class CountNWaysforSteps {
// running time O(3 ^ n) inefficient solution
public static int numberOfWays(int n){
if(n < 0 ) return 0;
if(n == 0 ) return 1;
return numberOfWays(n-1) + numberOfWays(n-2) + numberOfWays(n-3);
}
//memoized solution running time O(N)
public static int numberOfWaysMemoized(int n, Map<Integer,Integer> cache){
if(n < 0 ) return 0;
if(n == 0 ) return 1;
if(cache.containsKey(n)){
return cache.get(n);
}
int calculatedNumberOFWays = numberOfWaysMemoized(n-1, cache) + numberOfWaysMemoized(n-2, cache) + numberOfWaysMemoized(n-3, cache);
cache.put(n,calculatedNumberOFWays);
return calculatedNumberOFWays;
}
public static void main(String...args){
System.out.println(numberOfWays(5));
System.out.println(numberOfWaysMemoized(5, new HashMap<>()));
}
}