【问题标题】:min cost of climbing stairs dynamic programming爬楼梯的最小成本动态规划
【发布时间】: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]);
    }
};

如您所见,我在代码末尾进行了更改

【问题讨论】:

  • 有没有使用递归的解决方案?

标签: c++ dynamic-programming


【解决方案1】:

问题在于递归缺少基本情况。 currStair 在每次递归调用中不断递减 -1 或 -2,但没有条件检查它是否低于 0 并切断递归,从而导致像 minCost[-1] 这样的非法内存访问。

添加前置条件

if (currStair < 0) return 0;

虽然算法仍有正确性问题需要解决,但您又回到了正轨。

以下提示可能会帮助您摆脱困境:

说明说:“您需要找到到达楼层顶部的最低成本,您可以从索引为 0 的台阶开始,也可以从索引为 1 的台阶开始。”

【讨论】:

  • 您好,谢谢您的回复。你能检查我上面编辑的解决方案吗?我仍然卡住了,但我知道问题出在哪里。我只是不知道如何解决它。 (如果说输入是 [1,3],我将返回 3,因为我没有将它与第一个成本进行比较)
  • 我看到了更新。我发布的答案/提示仍然适用。话虽如此,问题一次只能问一件事,否则它会变成一堆移动的球门柱,对未来的读者没有太大帮助。因此,如果您遇到的问题超出了原来的“为什么会发生此运行时错误?”,我建议您提出一个新问题。似乎已解决的问题。见what to do when someone answers my question?
  • 太好了——当你发布它时,请随时指出我。我假设您已经查看了提示,但请考虑此代码如何处理“您可以从 0 或 1 开始”选项。你的代码会这样做吗?另外,你决定从后到前工作有什么特别的原因吗?我认为这样写的算法不太直观,因为它与问题描述不匹配。
  • 非常感谢,我会告诉你的。我决定自上而下地实施它,只是为了练习这两种方式。
  • 这里是我的新帖子的链接:stackoverflow.com/questions/59230399/…
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多