简体   繁体   English

C++ 递归来决定数组中的两个值

[英]C++ recursion to decide between two values in an array

I am trying to create a function that can increment either one or two moves ahead (whichever index contains a smaller integer) in an array to get to the last value using recursion.我正在尝试创建一个 function 可以在数组中增加一个或两个移动(无论哪个索引包含较小的整数)以使用递归到达最后一个值。 This is for an assignment, and I have been working for over a day to try and figure this out.这是一个任务,我已经工作了一天多来试图解决这个问题。 So I am not asking for the actual code to do this, but am looking for what's wrong in the code I have so far.所以我不是要求实际的代码来做这件事,而是在寻找我到目前为止的代码中的问题。 I put together a function that works, but does it incrementally.我将一个 function 放在一起,它可以工作,但它是渐进式的。

int findLowestSum(int arr[], int low, int high, int arrSize) {
    int minVal = 0;
    while (high < arrSize) {

        if (arr[low] < arr[high]) {
            minVal += arr[low];
            low += 1;
            high = low +1;
        }
        else {
            minVal += arr[high];
            low +=2;
            high = low +1;

        }
    }
    return minVal;
}

Here is what I have so far for the recursive version.这是我到目前为止的递归版本。 Without trying to make a bad recursion joke, I have been going around in circles on this for about a day.不想开一个糟糕的递归笑话,我已经在这个问题上绕了大约一天。

int findLowestSum(int arr[], int startIdx, int endIdx) {
    int minVal = 0;
    int res1, res2;
    int sum = 0;


    if (endIdx - startIdx <= 3)
        return sum += arr[endIdx];
    else {
        if (arr[startIdx+1] < arr[startIdx + 2]) {

            sum+= arr[startIdx+1];
            res1 = findLowestSum(arr, startIdx + 1, endIdx);


        }
        else {
            sum+= arr[startIdx+2];
            res2 = findLowestSum(arr, startIdx + 2, endIdx);

        }

    return sum + arr[endIdx];

    }


}

Any insight into what is actually happening with my recursive attempt, and where i need to fix would be greatly appreciated.任何对我的递归尝试实际发生的事情以及我需要修复的地方的任何见解都将不胜感激。

Try thinking with iterators instead of array indexes.尝试使用迭代器而不是数组索引来思考。 Then the solution becomes trivial:然后解决方案变得微不足道:

#include <iterator>

int findLowestSum(int const* begin, int const* const end) {
  if (begin >= end) return 0; // std::next(begin) would be UB
  auto const next = std::next(begin);
  if (next >= end) return 0;
  if (*begin >= *next) {
    begin = next;
  }
  return *begin + findLowestSum(std::next(begin),end);
}

This can be called with findLowestSum(std::begin(arr),std::end(arr)) .这可以用findLowestSum(std::begin(arr),std::end(arr))调用。

You only need the <iterator> header for std::next , std::begin and std::end .您只需要<iterator> header 用于std::nextstd::beginstd::end You can also rewrite this if you don't want the <iterator> dependency.如果你不想要<iterator>依赖,你也可以重写它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM