I have to calculate the number of ways one can climb a staircase taking 1, 2, or 3 steps at a time. I know of ways to do this, for example, f(n-1) + f(n-2) + f(n-3)
but I would like to know why in my implementation (which is different from the above) I do not get the correct answer. I'm using a for
loop instead.
The problem is every time a value is returned that is non-zero but that value includes a pre-calculated answer, and hence is not used by my code. What changes do I need to make?
#include <iostream>
#include <map>
using namespace std;
int nWays = 0;
int stepPerms(int n, map<int, int> &memo) {
if (memo.find(n) != memo.end())
return memo[n];
if (n == 0)
return 0;
if (n < 0)
return -1;
for (int i = 1; i <= 3; i++) {
int retVal = stepPerms(n - i, memo);
if (retVal == 0)
memo[n] = ++nWays;
}
return memo[n];
}
int main() {
map<int, int> memo;
cout << stepPerms(5, memo);//cout << stepPerms(3) << endl;
}
I solved it like this :
#include <iostream>
#include <map>
using namespace std;
map<int, int> memo;
int stepPerms(int n) {
if (memo.find(n) != memo.end())
return memo[n];
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 4;
for (int i = 1; i <= 3; i++)
memo[n] += stepPerms(n - i);
return memo[n];
}
int main() {
cout << stepPerms(27);
}