This is in fact closely related to the Fibonacci sequence, as was mentioned only briefly in one of the comments so far: Each step n
can be reached from either two steps below (n-2
) or one step below (n-1
), thus the number of possibilities to reach that step is the sum of the possibilities to reach those other two steps. Finally, there is exactly one possibility to reach the first step (and the zeroth, i.e. staying on the ground).
Also, as the number of possibilities for step n
depends only on the results for step n-1
and n-2
, it is not necessary to store all those intermediate values in a map or in an array -- the last two are enough!
public static long possForStep(int n) {
// current and last value, initially for n = 0 and n = 1
long cur = 1, last = 1;
for (int i = 1; i < n; i++) {
// for each step, add the last two values and update cur and last
long tmp = cur;
cur = cur + last;
last = tmp;
}
return cur;
}
This not only reduces the amount of code by a good share, but also gives a complexity of O(n) in time and O(1) in space, as opposed to O(n) in time and space when storing all the intermediate values.
However, since even the long
type will quickly overflow as n
approaches 100 anyway, space complexity of O(n) is not really a problem, so you can just as well go with this solution, which is much easier to read.
public static long possForStep(int n) {
long[] values = new long[n+1];
for (int i = 0; i <= n; i++) {
// 1 for n==0 and n==1, else values[i-1] + values[i-2];
values[i] = (i <= 1) ? 1 : values[i-1] + values[i-2];
}
return values[n];
}
Update: Note that this is close to, but not quite the same as the Fibonacci sequence, which starts 0, 1, 1, 2, 3,...
while this one goes 1, 1, 2, 3, 5, ...
, i.e. possForStep(n) == fibonacci(n+1)
.