I am trying to change the following algorithm from recursive to iterative, and am having problems doing so. (Book: "Cracking the Coding Interview.")
Question: "A child is running up a staircase with n steps, and can hop either 1, 2, or 3 steps at a time. Implement a method to count how many ways the child can run up the stairs."
Book's answer (recursive):
public static int countWays(int n, int[] map) {
if (n < 0)
return 0;
if (n == 0)
return 1;
if (map[n] > -1)
return map[n];
map[n] = countWays(n - 1, map) + countWays(n - 2, map) + countWays(n - 3, map);
return map[n];
}
My answer (iterative):
public static int countWays(int n, int[] map) {
for (int i = 1; i <= n; i++) {
//Problem with writing it this way: index could be negative
map[i] = map[i - 1] + map[i - 2] + map[i - 3];
}
return map[n];
}
One problem I am having with my given answer is that the line "map[i - 1] + map[i - 2] + map[i - 3]" could result in negative indices, which would throw an error.
There may be other problems with my code.
Could someone please help in writing this?