You are climbing a staircase. It takes
nsteps to reach the top.Each time you can either climb
1or2steps. In how many distinct ways can you climb to the top?Constraints:
1 <= n <= 45
Notice that the problem possesses the optimal substructure property. Let be the number of distinct ways to climb to the th step.
Thus, we have . Our base cases occurs when or , so the full Bellman Equation is
We first store all the solutions in a hash table, so they can be accessed in constant time. Then we work our way up from until we reach the desired step number, following the Bellman Equation:
def climbStairs(n: int) -> int:
solution = {}
for step in range(1, n + 1):
if step == 1 or step == 2:
solution[step] = step
else:
solution[step] = solution[step - 1] + solution[step - 2]
return solution[n]
This is a non-recursive bottom-up approach, so we calculate the time complexity of the for loop. Each iteration takes constant time (if statement and assignments with constant lookup time of the hash table), and there are iterations. Thus, the total complexity is in .
We store the number of distinct ways to reach each step below , which is constant. Since there are elements we must store, the total space complexity is .
Notice that each call only uses the previous 2 ways—and we only care about the very last step! Thus, there is no need to store the distinct ways for every step, and we can store only the previous 2 steps.
def climbStairs(n: int) -> int:
if n < 3: return n
minus1, ways = 1, 2
for step in range(3, n + 1):
minus1, ways = ways, ways + minus1
return ways
We now have the same time complexity of but a space complexity in !