【发布时间】:2019-12-07 21:30:05
【问题描述】:
我正在尝试解决 Leetcode 上的以下问题:
在楼梯上,第 i 个步骤有一些非负成本
cost[i]分配(0 索引)。支付费用后,您可以爬上一级或两级台阶。 您需要找到到达楼层顶部的最低成本,您可以从索引为 0 的台阶开始,也可以从索引为 1 的台阶开始。
到目前为止,这是我的解决方案。我相信我没有正确考虑到我可以从 0 级或 1 级开始这一事实,而且我不知道该怎么做。
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return helper(cost, cost.size() - 1);
}
int helper(vector<int>& cost, int currStair) {
static vector<double> minCost(cost.size(), 0);
minCost[0] = cost[0];
minCost[1] = cost[1];
if (currStair < 0 || cost.size() <= 1) {
return 0;
}
if (minCost[currStair] > 0) {
return minCost[currStair];
}
return minCost[currStair] = min(helper(cost, currStair - 1), helper(cost, currStair - 2)) + cost[currStair];
}
};
【问题讨论】:
标签: c++ algorithm recursion dynamic-programming