【问题标题】:Finding the highest difference of pairs recursive in C / C++ [closed]在C / C ++中找到递归对的最大差异[关闭]
【发布时间】:2018-06-22 22:32:38
【问题描述】:

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

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,因为它是最高的接近对差。 帮我! 谢谢!

【问题讨论】:

  • theBigNum(arr, 6); 所以数组的大小是 6?
  • 您对问题的描述令人困惑。您的意思是相邻对的差异,而不是总和。
  • 语言无所谓 C 或 C++
  • 我的数组是动态的,我给出了大小的例子
  • 你冒着被经常反对双重标签的人反对的风险。背景见这里:meta.stackoverflow.com/questions/361795/…

标签: c++ c recursion


【解决方案1】:
#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++ 递归解决方案。

【讨论】:

  • :-) 有点刻薄和卑鄙,但合适。
  • @Lejik007 如果你在任何地方遇到这个问题,请务必能够解释该答案中的每一行,不要落入 bolov 为你挖的陷阱。跨度>
  • 也许是其他人,请简单方法
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2019-04-09
  • 2021-12-08
  • 1970-01-01
  • 2016-09-12
  • 2010-10-12
  • 2016-04-17
  • 1970-01-01
相关资源
最近更新 更多