我对递归仍然很陌生,我想从此数组int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21}
返回3,以实现与递归实现相同的绝对值。
但是,我得到的值为0。我无法查明是什么使该程序没有带来期望的值。
#include <iostream>
using namespace std;
int additive_inverse_opposite_pairs_count(int* arr, int n) {
int size = n;
if (n == 0) {
if (arr[n] == -1 * arr[size - 1 - n])
return 1;
else
return 0;
} else {
int count = additive_inverse_opposite_pairs_count(arr, n - 1) + count;
if (arr[n] == -1 * arr[size - 1 - n]) {
count += 1;
} else
count = 0;
return count;
}
}
int main() {
int size = 8;
int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21};
int value = 0;
value = additive_inverse_opposite_pairs_count(arr, size);
cout << "value: " << value << endl;
return 0;
}
最佳答案
问题的一部分是您正在访问arr[n]
,其中n
是数组的大小。数组的有效索引是0..n-1
,因此您需要在arr[n]
语句的arr[n-1]
部分中将else
更改为if
。
一种想法是简单地从索引i
开始,从该点开始扫描数组的其余部分以寻找加性逆,如果找到,则返回该数字,否则进一步递归到数组中。我编写了一个辅助函数来完成这项工作。
int helper(int* arr, int i) {
if (i == 0) {
return 0;
}
for (int j = i - 1; j >= 0; j--) {
if (arr[i] == -arr[j]) {
return abs(arr[i]);
}
}
return helper(arr, i - 1);
}
int additive_inverse_opposite_pairs_count(int* arr, int n) {
return helper(arr, n - 1);
}
关于c++ - 实现递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60556961/