Dynamic programming states
Count ways of climbing n stairs with jumps of one or two. One empty route reaches stair zero. For signed 64-bit answers use 0 ≤ n ≤ 91.
| State | ways[i] | Count routes ending exactly on stair i |
| Base | ways[0] = ways[1] = 1 | The empty route and one single jump |
| Transition | ways[i−1] + ways[i−2] | Last choices are disjoint |
| Storage | Two preceding states | O(n) time, O(1) auxiliary words |
Python
def stairs(n):
a, b = 1, 1
for i in range(2, n+1):
a, b = b, a+b
return bC++
long long stairs(int n) {
long long a = 1, b = 1;
for (int i = 2; i <= n; ++i) {
long long next = a+b; a = b; b = next;
}
return b;
}Java
static long stairs(int n) {
long a = 1, b = 1;
for (int i = 2; i <= n; i++) {
long next = a+b; a = b; b = next;
}
return b;
}