c++ - 为什么我在 leetcode 上收到 AddressSanitizer: heap-buffer-overflow on address 0x602000000058 错误?
问题描述
我已经阅读了一些其他答案并查看了关于 codeforces 的博客。所有人都认为它一定是一些潜在的溢出。我已经对从 n = 1 到 n = 45 的所有测试用例进行了测试。我没有看到溢出。
class Solution {
public:
int checkSteps(int n, vector<int>&cache){
if(n <= 0)
return cache[0];
else if(n == 1){
return cache[1];
}
else if(n == 2){
return cache[2];
}
if(cache[n] > 0) return cache[n];
cache[n] = checkSteps(n-1, cache) + checkSteps(n-2, cache);
return cache[n];
}
int climbStairs(int n){
vector<int> cache(n+1, 0);
cache[0] = 0;
cache[1] = 1;
cache[2] = 2;
int result = checkSteps(n, cache);
return result;
}
解决方案
您也可以使用 Fib 数公式(黄金比例)来解决这个问题,将被接受:
struct Solution {
static const inline int climbStairs(const int n) {
double ways = 1 / pow(5, 0.5) * (pow((1 + pow(5, 0.5)) / 2, -~n) - pow((1 - pow(5, 0.5)) / 2, -~n));
return (int) ways;
}
};
-~n
只是(n + 1
),只是有点短
或根据您的方法,我们将迭代:
struct Solution {
static const inline int climbStairs(const int n) {
int first = 1;
int second = 0;
int ways = 0;
for (int iter = 0; iter < n; iter++) {
ways = first + second;
second = first;
first = ways;
}
return ways;
}
};
参考
如果你正在准备面试:
推荐阅读
- linux - Linux 命令显示您的机器拥有的硬盘驱动器插槽数
- amazon-web-services - 将存储桶策略附加到无服务器生成的存储桶
- r - 使用 RStudio 的“转到函数”进行记忆
- docker - 在 Gitlab-CI 上部署 jhipster 5.1.0 项目时出现“./gradlew: Permission denied”
- python-3.x - 如何将输入从 tkinter 存储到数据库
- amazon-web-services - 了解 AppSync + S3 如何协同工作
- move - 将 OctoberCMS 网站从 Ubuntu 虚拟机移动到 CentOS 7 虚拟机
- hashicorp-vault - Hashicorp Vault 社区版文件系统后端的加密细节
- c++ - 在 C++ 中交换输出引用参数和局部变量的风险
- uwp - UWP:无法从代码隐藏访问菜单复选框