DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

1 2

LeetCode in Ruby: 70. Climbing Stairs

Dynamic Programming

def climb_stairs(n)
  p = 1
  q = 1

  (n - 1).times do
    temp = q
    q += p
    p = temp
  end

  q
end

This problem can be solved by using dynamic programming. We define f(n) as the number of ways you climb to the nth step from:

  1. one step from n-1th step or,
  2. two steps from n-2th steps.

Therefore, f(n) = f(n-1) + f(n-2), which is the same as the Fibonacci sequence. We have two bases cases: f(1) = 1 and f(2) = 2. The lines 4 and 5 are the first two numbers of the Fibonacci sequence. To get the nth number, we add up the numbers up to nth number. Here, we optimize the performance the just storing the previous two numbers.

Time complexity: O(n)

Extra memory: O(1)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay