题目描述:数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 costi。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 1:
输入: cost = [10, 15, 20]
输出: 15
示例 2:
输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6 解释:
最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
注意:
cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
【Tips】:动态规划问题
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
/*使用最小花费爬楼梯*/
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> cm(n + 1); //Top means above the last stair
//Edge Case
if (n<2) return 0;
//Can either start from index 0 or 1
cm[0] = 0;
cm[1] = 0;
//DP to find the minimum cost to reach the last stair or second last stair
for (int i = 2; i <= n; i++)
cm[i] = min(cm[i - 2] + cost[i - 2], cm[i - 1] + cost[i - 1]);
//Cost to reach the stair above the last
return cm[n];
}
};
int main()
{
vector<int> tmp(10);
tmp[0] = 1; tmp[1] = 100; tmp[2] = 1; tmp[3] = 1; tmp[4] = 1;
tmp[5] = 100; tmp[6] = 1; tmp[7] = 1; tmp[8] = 100; tmp[9] = 1;
//int n = sizeof(tmp) / sizeof(tmp[0]);
Solution solu;
int test = solu.minCostClimbingStairs(tmp);
cout << test<<endl;
//getchar();
system("pause");
return 0;
}