https://leetcode.com/problems/min-cost-climbing-stairs/description/
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
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.
Constraints:
- 2 <= cost.length <= 1000
- 0 <= cost[i] <= 999
애증의 DP다.
그래도 쉬운 Dynamic programming 문제이니까 으쌰으쌰 풀어보자
1. Python
뭐.. leetcode 자체적인 hint를 보고 풀었다.
LLM은 안 썼지만,, 그래도 찝찝하구먼
앞으론 leetcode 자체 hint도 미루고 미루다가 봐야겠다.
class Solution:
def minCostClimbingStairs(self, cost: list[int]) -> int:
dp = [0]*(len(cost)+2)
for i in range(len(cost)-1,-1,-1):
dp[i] = cost[i] + min(dp[i+1],dp[i+2])
return min(dp[0],dp[1])
2. C++
같은 맥락으로 쉽게 풀 수 있다.
#include <vector>
using namespace std;
#include <algorithm>
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> dp(n+2,0);
for(int i=n-1;i!=-1;i--){
dp[i] = cost[i] + min(dp[i+1],dp[i+2]);
}
return min(dp[0],dp[1]);
}
};
3. C
반대로 밑에서부터 올라가게도 풀어보기!
참고로 삼항 연산자(ternary operator)의 경우, C/C++은 a<=b ? a : b 이런식으로 쓰지만,
Python에선 조건 표현식으로 a if a <=b else b 이렇게 좀 더 가독성 좋게 쓴다.
int min(int a, int b){
return a <= b ? a : b;
}
int minCostClimbingStairs(int* cost, int costSize) {
int dp[costSize];
dp[0] = cost[0];
dp[1] = cost[1];
for(int i=2;i<costSize;i++){
dp[i] = min(dp[i-1],dp[i-2]) + cost[i];
}
return min(dp[costSize-1],dp[costSize-2]);
}
'Coding_Practice' 카테고리의 다른 글
Maximal Square(Array,Dynamic Programming,Matrix) (0) | 2024.11.13 |
---|---|
Min Cost to Connect All Points(Array,Union Find,Graph,Minimum Spanning Tree) (0) | 2024.11.12 |
Valid Palindrome(Two Pointers,String) (2) | 2024.11.11 |
Minimum One Bit Operations to Make Integers Zero[Dynamic Programming,Bit Manipulation,Memoization] (2) | 2024.11.08 |
Exam Room[Design,Heap (Priority Queue)Ordered Set] (1) | 2024.11.08 |