Easy Dynamic Programming

Climbing Stairs

Receives a non-negative integer n, the number of stairs in a staircase, and returns the number of distinct ways to reach the top when each move is either 1 or 2 steps. It computes the answer with bottom-up dynamic programming: the number of ways to reach step k is the sum of the ways to reach the two steps before it (ways(k) = ways(k-1) + ways(k-2)), so it fills that recurrence iteratively from the base cases ways(0) = ways(1) = 1 up to n, using two rolling variables instead of recursion. Returns the single integer ways(n); n ≤ 1 returns 1 directly (a staircase of zero or one step has exactly one trivial way to climb it).

Visualization

Input

Algorithm code

Custom input

Saved inputs

References