imashutosh51

Climibing stairs

Mar 25th, 2026
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. """
  2. Intuition:
  3. To reach the i-th step, you have only two possible moves:
  4. 1. Come from (i-1)-th step by taking 1 step
  5. 2. Come from (i-2)-th step by taking 2 steps
  6.  
  7. So, total ways to reach step i =
  8.    ways(i-1) + ways(i-2)
  9.  
  10. This works because:
  11. - All paths that end at (i-1) can extend by 1 step
  12. - All paths that end at (i-2) can extend by 2 steps
  13. - These two sets are disjoint and cover all possibilities
  14.  
  15. Base cases:
  16. ways(1) = 1
  17. ways(2) = 2
  18. """
  19. class Solution:
  20.     def climbStairs(self, n: int) -> int:
  21.         if n <= 2:
  22.             return n
  23.        
  24.         prev1 = 1  # ways to reach step 1
  25.         prev2 = 2  # ways to reach step 2
  26.        
  27.         for i in range(3, n + 1):
  28.             curr = prev1 + prev2
  29.             prev1 = prev2
  30.             prev2 = curr
  31.        
  32.         return prev2
Advertisement
Add Comment
Please, Sign In to add comment