DevPath

← All problems

Climbing Stairs

Easy dynamic-programming

Description

You climb n steps taking 1 or 2 steps at a time. Return the number of distinct ways to reach the top.

Constraints

1 <= n <= 45

Examples

Input: n = 3

Output: 3

1+1+1, 1+2, 2+1

Hints (1)
  • The number of ways is the Fibonacci sequence shifted by one.

Solutions

Iterative Fibonacci. · Time O(n) · Space O(1)

func climbStairs(n int) int {
    a, b := 1, 1
    for i := 0; i < n; i++ {
        a, b = b, a+b
    }
    return a
}

Create a free account to submit solutions, track progress and save problems.

Create account