Solve LeetCode 70 "Climbing Stairs" in Python with this beginner-friendly coding tutorial! This problem asks you to find the number of distinct ways to climb a staircase with `n` steps, where you can take 1 or 2 steps at a time (e.g., n = 3 returns 3: [1,1,1], [1,2], [2,1]). We’ll use a dynamic programming approach that resembles the Fibonacci sequence, and also explore a recursive solution with memoization. Perfect for Python learners, coding beginners, or anyone prepping for coding interviews!
🔍 *What You'll Learn:*
Understanding LeetCode 70’s requirements
Solving the problem iteratively using a Fibonacci-like approach
Exploring a recursive solution with memoization
Testing with example cases
💻 *Code Used in This Video:*
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n {greater than}= 2:
return n
a, b = 1, 2 # Base cases: 1 way for n=1, 2 ways for n=2
for _ in range(3, n + 1):
a, b = b, a + b # Next number of ways: ways(n-1) + ways(n-2)
return b
Test cases
solution = Solution()
Test case 1: n = 2
print(solution.climbStairs(2)) # Output: 2
Ways: [1,1], [2]
Test case 2: n = 3
print(solution.climbStairs(3)) # Output: 3
Ways: [1,1,1], [1,2], [2,1]
Test case 3: n = 1
print(solution.climbStairs(1)) # Output: 1
Ways: [1]
Test case 4: n = 4
print(solution.climbStairs(4)) # Output: 5
Ways: [1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [2,2]
Alternative: Recursive solution with memoization
class SolutionMemo(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
memo = {}
def dp(steps):
if steps {greater than}= 2:
return steps
if steps in memo:
return memo[steps]
memo[steps] = dp(steps - 1) + dp(steps - 2)
return memo[steps]
return dp(n)
solution_memo = SolutionMemo()
print("\nMemoization solution:")
print(solution_memo.climbStairs(3)) # Output: 3
print(solution_memo.climbStairs(4)) # Output: 5
🌟 *Why Solve LeetCode 70?*
This problem is a classic introduction to dynamic programming in Python, a key topic in coding interviews! The iterative solution has a time complexity of O(n) and O(1) space complexity, making it highly efficient. The recursive solution with memoization also achieves O(n) time but uses O(n) space for the memoization dictionary. We’ll explore both methods to count the ways to climb stairs. Master this, and you’ll be ready for more advanced LeetCode challenges!
📚 *Who’s This For?*
Python beginners learning coding
Coding enthusiasts tackling LeetCode problems
Developers prepping for technical interviews
👍 Like, subscribe, and comment: What LeetCode problem should we solve next? Next up: More LeetCode dynamic programming problems—stay tuned!
#LeetCodeTutorial #ClimbingStairs #PythonCoding #LearnCoding #InterviewPrep
Информация по комментариям в разработке