Algorithm Puzzles: Climbing Stairs
Algorithm Puzzles everyday every week sometimes: Climbing Stairs
Puzzle
Puzzle from leetcode:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Solution
It’s an easy puzzle can be resolved via dynamic programming:
- dp[1] = 1
- dp[2] = 2
- dp[3] = dp[1] + dp[2]
- dp[n] = dp[n-1] + dp[n-2]
1 | class Solution: |
TC should be O(n) and SC should be O(1).