在C++中,递归函数可能会导致栈溢出或性能下降。为了优化递归函数,您可以尝试以下方法:
int factorial(int n, int accumulator = 1) {
if (n == 0) {
return accumulator;
} else {
return factorial(n - 1, n * accumulator);
}
}
#include <unordered_map>
int fibonacci(int n, std::unordered_map<int, int>& memo) {
if (n <= 1) {
return n;
}
if (memo.find(n) == memo.end()) {
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
}
return memo[n];
}
int fibonacci(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1, c;
for (int i = 2; i <= n; ++i) {
c = a + b;
a = b;
b = c;
}
return b;
}
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
尝试根据您的具体问题和需求选择合适的优化方法。