[英]Why am I getting AddressSanitizer: heap-buffer-overflow on address 0x602000000058 error on leetcode?
I have read few other answers and checked a blog on codeforces.我已经阅读了一些其他答案并查看了关于 codeforces 的博客。 All suggest that it must be some potential overflow.
所有人都认为它一定是一些潜在的溢出。 I have tested it for all the testcases from n = 1 to n = 45. I don't see that overflow.
我已经对从 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;
}
You can also use the Fib Number formula ( Golden Ratio ) for this problem, will get accepted:您也可以使用 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
is simply ( n + 1
), just a bit shorter -~n
很简单( n + 1
),只是短一点or based on your approach, we would just iterate:或根据您的方法,我们将迭代:
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.