你可以选择从下标为 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 。
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cost int整型一维数组 * @param costLen int cost数组长度 * @return int整型 */ #include <stdio.h> int minCost(int number1,int number2) { if (number1<number2) { return number1; } else { return number2; } } int minCostClimbingStairs(int* cost, int costLen ) { // write code here if (costLen==1) { return cost[costLen-1]; } else { int dp[costLen]; //考虑是第一步是走一步还是两步 dp[0]=cost[0]; dp[1]=cost[1]; for (int i=2;i<costLen;i++) { //考虑到i所需要的金币数 //首先考虑走i //dp[i]=minCost(dp[i-1],dp[i-2])+cost[i] //然后考虑不走i //dp[i]=dp[i-1]+cost[i+1] dp[i]=minCost(minCost(dp[i-1],dp[i-2])+cost[i],dp[i-1]+cost[i+1]); printf("%d",dp[i]); } //最后直接返回到最后一个需要花费的金币数 return dp[costLen-1]; } }
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写发现时间也超了,官方就完全不给活路呗。