题目描述
给定一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用,下标从0开始。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
数据范围:数组长度满足
1
≤
n
≤
1
0
5
1 ≤ n ≤10^5
1≤n≤105
数组中的值满足
1
≤
c
o
s
t
[
i
]
≤
1
0
4
1≤ cost[i] ≤10^4
1≤cost[i]≤104
输入描述:
第一行输入一个正整数 n ,表示数组 cost 的长度。
第二行输入 n 个正整数,表示数组 cost 的值。
输出描述:
输出最低花费
示例1
输入:
3
2 5 20
输出:
5
说明:你将从下标为1的台阶开始,支付5 ,向上爬两个台阶,到达楼梯顶部。总花费为5
示例2
输入:
10
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 。
题目链接
核心代码模式
NC296 最小花费爬楼梯
ACM 模式
DP4 最小花费爬楼梯
状态方程
s t e p [ i ] = m i n ( s t e p [ i − 1 ] + c o s t [ i − 1 ] , s t e p [ i − 2 ] + c o s t [ i − 2 ] ) step[i] = min(step[i - 1] + cost[i - 1], step[i - 2] + cost[i - 2]) step[i]=min(step[i−1]+cost[i−1],step[i−2]+cost[i−2])
我的题解
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cost int整型vector
* @return int整型
*/
int minCostClimbingStairs(vector<int>& cost)
{
int csz = cost.size();//cost size
auto step = new int[csz + 1];
step[0] = step[1] = 0;//初始化
for (int i = 2; i <= csz; ++i)
{
step[i] = min(step[i - 1] + cost[i - 1], step[i - 2] + cost[i - 2]);
}
int ret = step[csz];
delete [] step;
return ret;
}
};
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cin >> n;
auto step = new int[n + 1];
auto cost = new int[n];
step[0] = step[1] = 0;
for(int i = 0; i < n; ++i)
cin >> cost[i];
for(int i = 2; i <= n; ++i)
{
step[i] = min(step[i - 1] + cost[i - 1], step[i - 2] + cost[i - 2]);
}
cout << step[n] << endl;
delete [] step;
delete [] cost;
return 0;
}
写在最后:题目中的new/delete可以直接用数组实现