You are given an integer array where is the cost of 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.
int minCostClimbingStairs(int* cost, int costSize){
}
本題是 Dynamic Programming的第三題,跟[70. Climbing Stairs]一樣給了一個n階樓梯,但也給一個陣列代表你在每一階代價來繼續前進,一開始可以選擇從0階出發也可以從1階出發,之後每一步都可以選擇一次走一階或一次走二階 (只要你付出了陣列裡該階的代價),最後需要求出最小的代價來爬到最高階,初見時真是沒有想法,於是參考網路上的做法[LeetCode] 746. Min Cost Climbing Stairs 爬楼梯的最小损失,說明如下:
程式碼上傳
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
int minCostClimbingStairs(int* cost, int costSize){
int dp[1001] = {0};
dp[0] = 0;
dp[1] = 0;
for (int i=2; i<costSize+1; i++) {
dp[i] = MIN(cost[i - 1] + dp[i - 1], cost[i - 2] + dp[i - 2]);
}
return dp[costSize];
}
第21天的旅程先到這裡,謝謝大家!