[leetcode] 70. Climbing Stairs

섬섬's 개발일지·2022년 1월 24일
0

leetcode

목록 보기
4/23

70. Climbing Stairs(Easy)

문제

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
Output : 2
Explanation : There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2

Input : n = 3
Output : 3
Explanation : There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 step
3. 2 step + 1 step

Constraints

  • 1<= n <= 45

풀이

Down-top 형식의 DP 문제이다.

  1. 1번째 계단으로 올라갈 수 있는 방법은 0번째에서 1칸만 올라오는 방법 뿐이다.
    즉, steps[1] = 1

  2. 2번째 계단으로 올라갈 수 있는 방법은 0번째에서 2칸 올라오거나, 1번째 칸에서 1칸 올라오는 방법이 있다.

    즉, steps[2]는 steps[0] + steps[1]이다. steps[1]은 1번째 계단까지 오는 방법의 개수이고, steps[0]은 0번째 계단까지 오는 방법의 개수이며, steps[2]로 가기 위해서 1칸을 이동할지 2칸을 이동할지만 다르기 때문에 두 개는 다른 경로이다.

  3. 따라서 steps[3] = steps[1] + steps[2] = 3이다.

코드

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        steps = [0] * (n+1)
        steps[0] = 1
        steps[1] = 1
        
        if n < 2 : return 1
        for i in range(2, n+1) :
            steps[i] = steps[i-2] + steps[i-1]
        
        return steps[n]
            
        
profile
섬나라 개발자

0개의 댓글