Problem 530879 · easy · Level 05 Advanced Algorithms & Graphs

Stairs in Ones and Twos

dynamic programming · 1d dp · fibonacci

Dynamic programming starts with a question: if I knew the answers for smaller inputs, could I build the answer for this one? Here the answer is yes, and the naive recursion is so slow that the speed-up is obvious.

A staircase has n steps, and every hop takes you up either 1 step or 2 steps. The same hops in a different order make a different route. Write climb_stairs(n) that counts the routes that end exactly on the top step.

Examples

Input:  n = 4
Output: 5
Explanation: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2

Input:  n = 1
Output: 1
Explanation: a single 1-step hop

Constraints

  • 1 <= n <= 45
  • Target: O(n) time, O(1) extra space (plain recursion without memoization is far too slow for n = 45)

Goals

  • Write a recurrence: express the answer for n in terms of smaller answers
  • Recognise overlapping subproblems and replace exponential recursion with a table or two variables
  • Build a bottom-up 1D DP from base cases
Starting Python…