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

์ฝ”๋”ฉํ…Œ์ŠคํŠธ/LeetCode

[LeetCode] Min Cost Climbing Stairs

๋ฌธ์ œ๋งํฌ

 

Min Cost Climbing Stairs - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ด๋™์„ ์œ„ํ•œ cost๊ฐ’์ด ์š”์†Œ๋กœ ๋“ค์–ด์žˆ๋Š” cost ๋ฐฐ์—ด์ด ์ฃผ์–ด์งˆ๋•Œ cost ๋ฐฐ์—ด์„ ๋๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ์†Œ์š”๋˜๋Š” ๋น„์šฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

์กฐ๊ฑด : ํ•œ๋ฒˆ์— index 1์นธ ๋˜๋Š” 2์นธ์„ ๊ฑด๋„ ์ˆ˜ ์žˆ๋‹ค.

์ ‘๊ทผ ๋ฐฉ๋ฒ•

์ „ํ˜•์ ์ธ dp ๋ฌธ์ œ์ด๋‹ค.

์ ํ™”์‹ => dp[i] += Math.min(dp[i-1], dp[i-2]) + cost[i]
dp[i-1], dp[i-2]๋Š” ํ˜„์žฌ๊นŒ์ง€ ์ง€๋ถˆํ•œ ๋น„์šฉ์ด๊ณ , cost[i]๋Š” ํ˜„์žฌ ์œ„์น˜์—์„œ์˜ ๋น„์šฉ์ด๋‹ค.
dp[0] = cost[0];
dp[1] = cost[1];

for(let i = 2; i < cost.length; i++){
    dp[i] += Math.min(dp[i-1], dp[i-2]) + cost[i];
}โ€‹


ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋ฅผ ํ†ตํ•ด ์˜ˆ๋ฅผ ๋“ค๋ฉด
[1,100,1,1,1,100,1,1,100,1]์„ ์ ํ™”์‹์„ ํ†ตํ•ด ๊ฐ’์„ ๋„์ถœํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฐ’์ด ๋‚˜์˜จ๋‹ค.
[1, 100, 2, 3, 3, 103, 4, 5, 104, 6]


โ€ป ๋‹ค๋ฅธ ํ’€์ด
dp ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ๋’ค์—์„œ๋ถ€ํ„ฐ ๊ฐ’์„ ์ฐพ๋Š” ๋ฐฉ๋ฒ•์„ ๋ฐœ๊ฒฌํ•˜์˜€๋‹ค.
for (let i = cost.length - 3; ~i; i--){
    cost[i] += Math.min(cost[i+1], cost[i+2])
}โ€‹

๋”ฐ๋กœ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜์ง€ ์•Š์•„ ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์„ฑ์ด ๋” ์ข‹์€ ์ฝ”๋“œ์ด๋‹ค.

[1,100,1,1,1,100,1,1,100,1]์„ ์ฝ”๋“œ๋ฅผ ๋Œ๋ฆฌ๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฐ’์ด ๋‚˜์˜จ๋‹ค.

[6, 105, 5, 5, 4, 102, 3, 2, 100, 1]

 

// ๋‚˜์˜ ํ’€์ด

/**
 * @param {number[]} cost
 * @return {number}
 */
var minCostClimbingStairs = function(cost) {
    let dp = new Array(cost.length).fill(0);
    
    dp[0] = cost[0];
    dp[1] = cost[1];
    
    for(let i = 2; i < cost.length; i++){
        dp[i] += Math.min(dp[i-1], dp[i-2]) + cost[i];
    }
    
    return Math.min(dp[cost.length-1], dp[cost.length-2])
};

 

// ๋‹ค๋ฅธ ํ’€์ด

/**
 * @param {number[]} cost
 * @return {number}
 */
var minCostClimbingStairs = function(cost) {
    for (let i = cost.length - 3; ~i; i--){
        cost[i] += Math.min(cost[i+1], cost[i+2])
    }
    return Math.min(cost[0], cost[1])
};

'์ฝ”๋”ฉํ…Œ์ŠคํŠธ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] Matchsticks To Square  (0) 2022.07.12
[LeetCode] Combination Sum  (0) 2022.07.11
[LeetCode] Single Number  (0) 2022.07.09
[LeetCode] Fibonacci Number  (0) 2022.07.06
[LeetCode] Longest Consecutive Sequence  (0) 2022.07.05