๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

IN DEPTH CAKE/Supercoder

[c++/LeetCode-DP] 70. Climbing Stairs

 

 

 

 

๋‚œ์ด๋„: Easy

ํ‚ค์›Œ๋“œ: DP

 

 

 

 

๐Ÿ“ ๋ฌธ์ œ

 

๊ณ„๋‹จ์„ ์˜ค๋ฅด๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ผญ๋Œ€๊ธฐ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•ด n๊ฐœ์˜ ๋‹จ๊ณ„๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
๊ฐ ๋‹จ๊ณ„๋งˆ๋‹ค 1๊ฐœ ๋˜๋Š” 2๊ฐœ์˜ ๋‹จ๊ณ„๋ฅผ ์˜ค๋ฅผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ผญ๋Œ€๊ธฐ์— ๋„๋‹ฌํ•˜๋Š” ๋ฐ ๋ช‡ ๊ฐ€์ง€ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์ด ์žˆ๋Š”์ง€ ๊ณ„์‚ฐํ•˜์„ธ์š”.

 

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

 

๋ฌธ์ œ ์›๋ฌธ: https://leetcode.com/problems/climbing-stairs/description/

 

๐Ÿ“ ๋ฌธ์ œ ํ’€์ด

 

๊ธฐ๋ณธ์ ์ธ DP ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋ฅผ ์žฌ๊ท€ ํ•จ์ˆ˜๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š”์ง€๋ฅผ ํŒŒ์•…ํ•œ ํ›„ Top-down. ํ˜น์€  Bottom-up ๋ฐฉ์‹์œผ๋กœ ํ•ด๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

์ผ๋ฐ˜์ ์œผ๋กœ Bottom-up์ด ๋” ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— bottom up์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งฐ๋‹ค.

 

a[n]์„ n๋ฒˆ์งธ ๊ณ„๋‹จ๊นŒ์ง€ ๊ฐ€๋Š” ๋ฐ ๊ฐ€๋Šฅํ•œ ๋ฐฉ๋ฒ• ์ˆ˜๋ผ๊ณ ํ•˜๋ฉด

a[n] = a[n-2] + a[n-1]์„ ๋งŒ์กฑํ•˜๋ฏ€๋กœ

 

class Solution {
public:
    int climbStairs(int n) {

        vector<int> a(n+1, 0);
        if(n == 1) return 1;
        if(n == 2) return 2;
        a[0] = 1;
        a[1] = 1;
        a[2] = 2;

        for(auto i = 3; i < (n+1); ++i){
            a[i] = a[i-1] + a[i-2];
        }

        return a[n];
    }
};

 

 

๋ฐ˜์‘ํ˜•