This algorithm is from Cracking the Coding Interview, 5th Edition, found here: https://www.geekbooks.me/book/view/cracking-the-coding-interview-5th-edition
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. Algorithm:
public static int countWaysDP(int n, int[] map) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
} else if (map[n] > -1) {
return map[n];
} else {
map[n] = countWaysDP(n - 1, map) +
countWaysDP(n - 2, map) +
countWaysDP(n - 3, map);
return map[n];
}
}
What is the time and space complexity of this algorithm? I think since memoization is used, the results are stored so values don't get calculated multiple times like in the pure recursive method. Since there are three calls to countWaysDP the time complexity is O(3n) which is an element of O(n). The space complexity would be O(n+n) one n for the size of map and one n for the recursive call stack, which is also an element of O(n). Is my reasoning correct?
Thanks