👨🏻‍💻알고리즘

[LeetCode] 70. Climbing Stairs

waveofmymind 2023. 2. 28. 10:23

문제 링크: https://leetcode.com/problems/climbing-stairs/submissions/

 

Climbing Stairs - LeetCode

Can you solve this real interview question? Climbing Stairs - 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?   Example 1: Input: n = 2 Outpu

leetcode.com

코드

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0,1,2]
        for i in range(3,n+1):
        	dp.append(dp[i-2]+dp[i-1])
        return dp[n]

 

풀이

  • 계단은 1칸, 2칸씩 오를 수 있으므로 2번 계단을 올라갈 때 까지의 경우의 수를 dp로 초기화해준다.
  • 계단을 오르는 방법의 경우의 수의 합은, 한칸 두칸씩 오르는 경우의 수의 합이므로 현재 i 번째 계단에서 -1,-2번 계단의 경우의 수를 더한 값과 같다.