【发布时间】:2020-04-01 09:53:52
【问题描述】:
我正在尝试解决leetcode上的以下问题:
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps.
You need to find minimum cost to reach the top of the floor, and you can either start
from the step with index 0, or the step with index 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 (minCost[currStair] > 0) {
return minCost[currStair];
}
return minCost[currStair] = min(helper(cost, currStair - 1), helper(cost, currStair - 2)) + cost[currStair];
}
};
当我尝试提交时,我收到以下运行时错误。为什么?
AddressSanitizer: heap-buffer-overflow on address 0x603000000008 at pc 0x0000004089af bp 0x7ffdd02dcaa0 sp 0x7ffdd02dca98
编辑解决方案:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return helper(cost, cost.size() - 1);
}
int helper(vector<int>& cost, int currStair) {
if (currStair < 0 || cost.size() <= 1) {
return 0;
}
static vector<double> minCost(cost.size(), 0);
minCost[0] = cost[0];
minCost[1] = cost[1];
if (minCost[currStair] > 0) {
return minCost[currStair];
}
minCost[currStair] = min(helper(cost, currStair - 1), helper(cost, currStair - 2)) + cost[currStair];
return min(minCost[cost.size()-1], minCost[cost.size()-2]);
}
};
如您所见,我在代码末尾进行了更改
【问题讨论】:
-
有没有使用递归的解决方案?