You climb a staircase of n steps, taking 1 or 2 steps at a time. How many distinct ways are there to reach the top?
Input
A single integer n.
Output
The number of distinct ways to climb n steps.
You climb a staircase of n steps, taking 1 or 2 steps at a time. How many distinct ways are there to reach the top?
A single integer n.
The number of distinct ways to climb n steps.
Example 1
2
2
1+1 or 2 — two ways.
Example 2
3
3
1+1+1, 1+2, 2+1 — three ways.
Example 3
5
8
Eight ways.
To reach step n you arrive either from step n-1 (a single step) or step n-2 (a double step).
So ways(n) = ways(n-1) + ways(n-2) — the Fibonacci recurrence.
Dynamic programming: ways(1) = 1, ways(2) = 2, ways(n) = ways(n-1) + ways(n-2). Iterate keeping the last two.
n = int(input())
a, b = 1, 1
for _ in range(2, n + 1):
a, b = b, a + b
print(b if n >= 1 else 1)
Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.