Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Climbing Stairs[Math,Dynamic Programming,Memoization]

eatplaylove 2024. 8. 20. 12:46

https://leetcode.com/problems/climbing-stairs/description/

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 steps
3. 2 steps + 1 step

 

Constraints:

  • 1 <= n <= 45

1. C

피보나치와 비슷한 개념이다.

int climbStairs(int n) {
    if( n<= 1) return 1;

    int dp[n+1];
    dp[0]=1;
    dp[1]=1;

    for(int i=2;i<=n;i++){
        dp[i] = dp[i-1]+dp[i-2];
    }

    return dp[n];
}

 

n번째에서 가능한 경우의 수는 n-2번째에서 2칸 올라가거나 n-1번째에서 1칸 올라가는 것뿐.

그래서 for문 안에 dp가 저렇게 형성된 것이다.

 

2. C++

# C++
class Solution {
public:
    int climbStairs(int n) {
        vector<int> dp(n+1,0);
        if(n<=3) return n;
        dp[1] = 1;
        dp[2] = 2;
        for(int i=3; i<=n; i++){
            dp[i] = dp[i-1]+dp[i-2];
        }
        return dp[n];
    }
};

 

3. Python

Python에선 공간복잡도를 O(N) -> O(1) 만들어보기

class Solution:
    def climbStairs(self, n: int) -> int:
        if n<=3 : return n
        prev1,prev2 = 1,2
        for i in range(3,n+1):
            ans = prev1 + prev2
            prev1 = prev2
            prev2 = ans
        return ans