[Algorithm] Leetcode_ 70 Climbing Stairs

JAsmine_log·2024년 5월 31일
0

70 Climbing Stairs

Problem

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

Solution

Code

C++ Recursion ( Time exeed! :( )

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

    int climbStairs(int n) {
        if ( n==0 || n == 1) return 1;
        return climbStairs(n - 2) + climbStairs(n - 1);    
    }
};

C++ Top-Down

// https://leetcode.com/problems/climbing-stairs/description/
class Solution
{
public:
    int memo[46] = {0};

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

        if (memo[n] != 0)
            return memo[n];

        return memo[n] = climbing_TopDown(n - 1) + climbing_TopDown(n - 2);
    }

    int climbing_BottomUp(int n)
    {

        int table[46] = {0};

        if (n == 0 || n == 1)
            return 1;
        // n=0 reutnr 1 becuase 2 = 1+1 or 2
        table[0] = 1;
        table[1] = 1;
        for (int i = 2; i <= n; i++)
        {
            table[i] = table[i - 1] + table[i - 2];
        }
        return table[n];
    }
    int climbStairs(int n)
    {
        // pick what you want
        //return climbing_BottomUp(n);
        //return climbing_TopDown(n);
        return 0;
    }
};
profile
Everyday Research & Development

0개의 댓글

관련 채용 정보