Climbing Stairs
Climbing Stairs
You are climbing a staircase that has n steps. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=3 → 3 (ways: 1+1+1, 1+2, 2+1) Example: n=5 → 8 Note: This is the Fibonacci sequence: f(n) = f(n-1) + f(n-2)
Input format — only if your code reads from stdin
Input format (stdin): - A single integer n (the total number of stairs) Output: a single integer — the number of distinct ways to climb to the top.
Approach
This is the Fibonacci sequence in disguise. dp[1]=1, dp[2]=2. For each step i from 3 to n: dp[i] = dp[i-1] + dp[i-2]. You can optimize space to two variables since you only need the last two values.
Input
Output
- •
1 ≤ n ≤ 45
More Dynamic Programming problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards