你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
数据范围:数组长度满足 ,数组中的值满足
[2,5,20]
5
你将从下标为1的台阶开始,支付5 ,向上爬两个台阶,到达楼梯顶部。总花费为5
[1,100,1,1,1,90,1,1,80,1]
6
你将从下标为 0 的台阶开始。 1.支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。 2.支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。 3.支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。 4.支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。 5.支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。 6.支付 1 ,向上爬一个台阶,到达楼梯顶部。 总花费为 6 。
int minCostClimbingStairs(int* cost, int costLen ) { // write code here // int ret = 0; int dp[costLen]; dp[0] = 0; dp[1] = 0; for(int i = 2; i <= costLen; i++){ dp[i] = (dp[i - 1] + cost[i - 1]) > (dp[i - 2] + cost[i - 2]) ? (dp[i - 2] + cost[i - 2]) : (dp[i - 1] + cost[i - 1]); } return dp[costLen]; }
#include <math.h> #include <stdlib.h> int minCostClimbingStairs(int* cost, int costLen ) { int *minCost = (int*)malloc(sizeof(int) * (costLen + 1)); minCost[0] = 0, minCost[1] = 0;//在clion里默认初始化为0,这里没有害我浪费半个小时 for(int i = 2; i <= costLen; i++){ minCost[i] = (int)fmin(cost[i - 1] + minCost[i - 1], cost[i - 2] + minCost[i - 2]); } return minCost[costLen]; }
int minCostClimbingStairs(int* cost, int costLen ) { // write code here if(costLen==1||costLen ==0) { return 0; } int count1 = minCostClimbingStairs(cost,costLen-1) + cost[costLen-1]; int count2 = minCostClimbingStairs(cost,costLen-2) + cost[costLen-2]; return count1<count2?count1:count2; }一开始用C++写发现时间超了,以为这道题只能用C写,用C写发现时间也超了,官方就完全不给活路呗。