Workspace Dynamic Programming
0d
DSA Cheat Sheets

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.

Stateways[i]Count routes ending exactly on stair i
Baseways[0] = ways[1] = 1The empty route and one single jump
Transitionways[i−1] + ways[i−2]Last choices are disjoint
StorageTwo preceding statesO(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 b

C++

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;
}