作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写最高对差异的递归代码,例如:我有这个代码,但我不想将我的答案保存到数组,并且我只需要包含两个运算符数组和大小的递归代码数组:
int theBigNum(int arr[], int i){
int tmpSum,sum = 0;
tmpSum = arr[i] - arr[i-1];
if (tmpSum < 0)
tmpSum = tmpSum * -1;
if (tmpSum > arr[6])
arr[6] = tmpSum;
if (i < 2)
return arr[6];
return theBigNum(arr, i - 1);
}
void main() {
int arr[7] = { 4, 6, -2, 10, 3, 1, 2};
int num = theBigNum(arr, 6);
}
返回的答案必须是12,因为它是最大的接近对差异。帮我!谢谢!
最佳答案
#include <cassert>
#include <iostream>
#include <vector>
#include <algorithm>
template <class It>
auto max_op(It begin, It end)
{
assert(begin != end);
auto next = std::next(begin);
assert(next != end);
auto s = std::abs(*begin - *next);
if (std::next(next) == end)
return s;
return std::max(s, max_op(next, end));
}
template <class Container>
auto max_op(const Container& c)
{
assert(c.size() >= 2);
return max_op(std::begin(c), std::end(c));
}
int main()
{
auto v = std::vector<int>{4, 6, -2, 10, 3, 1, 2};
auto m = max_op(v);
std::cout << m << std::endl; // 12
}
我回答这个问题是因为,如果你真的有兴趣学习,这会对你有所帮助,如果你只是想“给我一份作业的代码”,那么我唯一的遗憾是,当你向他提供此代码。
现在让我们把这个答案变成一个好的答案:
要使其递归地工作,您需要传递一个范围作为参数,并在每一步中计算您的操作(是的,我没有使用“sum”,想知道为什么)该范围的前 2 个元素。每个递归调用都会将范围缩小 1。步骤之间的链接当然是 std::max,因为您想要其中的最大值。
要停止递归,您有两种选择:在函数入口处设置停止条件以检查范围是否太短,或者在递归步骤处设置防护。虽然第一个更常见,但我避免了它,因为我们需要从函数中返回一些东西,而当我们有无效范围时返回一些东西是没有意义的。
这就是:一个简单且正确的 C++ 递归解决方案。
关于c++ - 在 C/C++ 中递归查找最大差值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48243598/
我的 C 代码有问题。我所做的就是这样: #include int main() { float zahlen[2]; for (int i = 0; i < 2; i++) {
我是一名优秀的程序员,十分优秀!