Solve the climbing stairs problem from leetcode in Python
- User
Solve the climbing stairs problem from leetcode in Python
Assistant
Here's the solution for the climbing stairs problem in Python, using dynamic programming:
class Solution: def climbStairs(self, n: int) -> int: if n <= 3: return n dp = [0 for _ in range(4)] dp[0], dp[1], dp[2], dp[3] = 1, 2, 3, 5 for i in range(4, n+1): dp[0], dp[1], dp[2], dp[3] = dp[1], dp[2], dp[3], dp[0] + dp[1] + dp[2] return dp[3]Explanation:
The problem is to find the number of unique ways to climb n stairs, where each step can be either 1 or 2 stairs. We can use dynamic programming to solve this problem.
We initialize a list of 4 integers, dp[0], dp[1], dp[2], dp[3], to store the number of unique ways to climb 1, 2, 3, and 4 stairs respectively.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.