Climbing stairs

You climb a staircase of n steps, taking 1 or 2 steps at a time. In how many different ways can you reach the top?

What to build

A program that counts the ways to climb n steps.

Requirements

  • Print the number of different sequences of 1-steps and 2-steps that add up to n.
  • Use a table, not plain recursion, which would repeat the same work.

Input

One integer n.

Output

The number of ways.

Constraints

1 ≤ n ≤ 45.

Example

Input:

2

Output:

2

Why it works

To stand on step i, the last move came from step i − 1 or step i − 2, so the ways add up. Each value is computed once from the two before it, which is O(n).

Examples

Example 1 · Input
2
Expected output
2
Example 2 · Input
3
Expected output
3

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

ways[i] = ways[i − 1] + ways[i − 2]: the last move was 1 step or 2 steps.

Hint 2

Base cases: ways[0] = 1 and ways[1] = 1.

Hint 3

Fill the table from 2 up to n.

Solution

Show one correct solution (try it yourself first)
n = int(input())
ways = [1, 1] + [0] * n
for i in range(2, n + 1):
    ways[i] = ways[i - 1] + ways[i - 2]
print(ways[n])

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Dynamic programming patterns →