给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。请你计算并返回达到楼梯顶部的最低花费。
示例 1:
输入:cost = [10,15,20]
输出:15
解释:你将从下标为 1 的台阶开始。
- 支付 15 ,向上爬两个台阶,到达楼梯顶部。
总花费为 15 。
示例 2:
输入:cost = [1,100,1,1,1,100,1,1,100,1]
输出:6
解释:你将从下标为 0 的台阶开始。
-
支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。
-
支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。
-
支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。
-
支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。
-
支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。
-
支付 1 ,向上爬一个台阶,到达楼梯顶部。
总花费为 6 。
提示:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
优化前:
采用递归的思路
int min(int x,int y)
{
return x>y?y:x;
}
int minCostClimbingStairs(int* cost, int costSize){
if(costSize<=1){
return 0;
}
return min(cost[costSize-1]+minCostClimbingStairs(cost,costSize-1),cost[costSize-
2]+minCostClimbingStairs(cost,costSize-2));
}
上面的代码虽然逻辑上没什么问题,但是数据量较大时运行时间较长,且每次都需重新计算一次,比较浪费资源。
优化后:
优化思路:1、递归过程过于浪费时间,每次都重新计算需要花费大量时间 $~~~~~~$2、空间换时间
int min(int x,int y)
{
return x>y?y:x;
}
int minCostClimbingStairs(int* cost, int costSize){
if(costSize<=1){
return 0;
}
int costArr[costSize+1];
memset(costArr,0,sizeof(costArr));
costArr[0]=0;
costArr[1]=0;
for(int i=2;i<costSize+1;i++){
costArr[i]=min(cost[i-2]+costArr[i-2],cost[i-1]+costArr[i-1]);
}
return costArr[costSize];
}