·
·
·
·
·
·
Brute force · recursion
▸1ways(i):2 if i <= 1: return 13 return ways(i−1) + ways(i−2) // recomputes!
state
- n5
- recurrenceways(i) = ways(i−1) + ways(i−2)
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemYou are climbing a staircase that takes n steps to reach the top. Each time you can climb 1 or 2 steps. In how many distinct ways can you reach the top?
▸1ways(i):2 if i <= 1: return 13 return ways(i−1) + ways(i−2) // recomputes!
line 1From step n you arrived either by a 1-step (from n−1) or a 2-step (from n−2). So ways(n) = ways(n−1) + ways(n−2), with ways(0) = ways(1) = 1. The obvious code is direct recursion.