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

IN DEPTH CAKE/Supercoder

[c++/LeetCode-DP] 746. Min Cost Climbing Stairs

 

๋‚œ์ด๋„: Easy

ํ‚ค์›Œ๋“œ: DP

 

 

 

 

์ •์ˆ˜ ๋ฐฐ์—ด cost๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ, cost[i]๋Š” ๊ณ„๋‹จ์˜ i๋ฒˆ์งธ ๋‹จ๊ณ„์˜ ๋น„์šฉ์ž…๋‹ˆ๋‹ค. ๋น„์šฉ์„ ์ง€๋ถˆํ•˜๋ฉด 1๊ฐœ ๋˜๋Š” 2๊ฐœ์˜ ๋‹จ๊ณ„๋ฅผ ์˜ค๋ฅผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ธ๋ฑ์Šค 0 ๋˜๋Š” ์ธ๋ฑ์Šค 1์˜ ๋‹จ๊ณ„์—์„œ ์‹œ์ž‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ตœ์ƒ์œ„ ์ธต์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ์†Œ ๋น„์šฉ์„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.

 

 

Example 1:

Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.

 

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.

 

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

 

 

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {

        const int N = cost.size();
        vector<int> a(N+1, 0);
        
        if(N <= 1) return 0;
        a[0] = 0;
        a[1] = 0;

        for(int n=2; n <= N; ++n){
            a[n] = min(a[n-1] + cost[n-1], a[n-2] + cost[n-2]);
        }

        return a[N];
        
    }
};

 

 

๋ฐ˜์‘ํ˜•