c++ - 在 C/C++ 中递归查找最大差值对

标签 c++ c recursion

我正在尝试编写最高对差异的递归代码,例如:我有这个代码,但我不想将我的答案保存到数组,并且我只需要包含两个运算符数组和大小的递归代码数组:

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/

相关文章:

java - 递归方法结束时变量保持设置为 1

c++ - C++ 对象是否具有固定大小?

c++ - IHTMLDocument2::get_body 在 IE 11 的 CHtmlView 中失败

c++ - 如何使用 pragma

c - C 中的变量重用

C 链表 - 在内存块中创建节点

c - 静态变量存储在哪里?

java - 使用递归添加到变量

javascript - 排序递归函数导致数组的数组

c++ - 如何在 C++ 中声明和初始化 BigDecimal