题解 | #最小花费爬楼梯#
最小花费爬楼梯
https://www.nowcoder.com/practice/6fe0302a058a4e4a834ee44af88435c7
不需要数组,如果数组长度大于2,就记录两个变量f,g。f为到达当前位置的消费,g为f前一个位置的消费。
f就为当前位置的最小消费,可得递推公式。
然后把 g 向前推进一位就行:。
int minCostClimbingStairs(int* cost, int costLen ) {
// write code here
if(costLen <= 2) return 0;
int f = 0, g = 0;
for(int i = 2; i <= costLen; i++){
int tmp = f;
f = g + cost[i-2] > f + cost[i - 1] ? f + cost[i - 1] : g + cost[i-2];
g = tmp;
}
return f;
}