I'm practicing replacing recursion with while loops, and I'm stuck on the following problem.
How many ways can you go up a staircase of length n if you can only take the stairs 1 or 2 at a time?
The recursive solution is pretty simple:
def stairs(n):
if n <= 1:
return 1
else:
return stairs(n-2) + stairs(n-1)
I feel like the structure for the iterative program should go something like this:
def stairs_iterative(n):
ways = 0
while n > 1:
# do something
ways +=1
return ways
But I don't know what I need to put in the #do something part. Can someone help me? Pseudocode is fine!
This amounts to the top-down (recursive) approach vs. the bottom-up (iterative) approach for dynamic programming.
Since you know that for input
n
you need all values ofstairs(p)
for0 <= p <= n
. You can iteratively computestairs(p)
starting atp = 0
until you reachp = n
, as follows:A different approach than @univerio is to use a list as stack: