双重调用递归(C ++)

时间:2015-08-16 16:14:09

标签: c++ recursion

有人可以向我解释这究竟是如何加起来的吗?

我对“双重呼叫”感到困惑。也许我只是不理解递归以及我认为我做过。

#include <iostream>
using namespace std;

int rec(int * N, int max) {
    if (max < 0)
        return 0;

    return N[max] + rec(N, max - 1) + rec(N, max - 2); 
}

int main() {
   const int max = 5;
    int N[] = { 1, 2, 3, 4, 5 };
    int f = rec(N, max - 1);

    cout << f << endl; 
   return 0;
}

1 个答案:

答案 0 :(得分:5)

int f = rec(N, 4)
      = N[4] + rec(N, 3) + rec(N, 2)
      = 5 + (N[3] + rec(N, 2) + rec(N, 1)) + (N[2] + rec(N, 1) + rec(N, 0))
      = 5 + (4 + (N[2] + rec(N, 1) + rec(N, 0)) + (N[1] + rec(N, 0) + rec(N, -1)) + (3 + (N[1] + rec(N, 0) + rec(N, -1)) + (N[0] + rec(N, -1) + rec(N, -2)))
      = 5 + (4 + (3 + rec(N, 1) + rec(N, 0)) + (2 + rec(N, 0) + 0) + (3 + (2 + rec(N, 0) + 0) + (1 + 0 + 0))
      = 5 + (4 + (3 + (N[1] + rec(N, 0) + rec(N, -1)) + (N[0] + rec(N, -1) + rec(N, -2))) + (2 + (N[0] + rec(N, -1) + rec(N, -2)) + 0) + (3 + (2 + (N[0] + rec(N, -1) + rec(N, -2)) + 0) + 1)
      = 5 + (4 + (3 + (2 + (N[0] + rec(N, -1) + rec(N, -2)) + 0) + (1 + 0 + 0)) + (2 + (1 + 0 + 0) + 0) + (3 + (2 + (1 + 0 + 0) + 0) + 1))
      = 5 + (4 + (3 + (2 + (1 + 0 + 0) + 0) + 1) + (2 + 1 + 0) + (3 + (2 + 1 + 0) + 1))
      = 5 + (4 + (3 + (2 + 1 + 0) + 1) + 3 + (3 + 3 + 1))
      = 5 + (4 + (3 + 3 + 1) + 3 + 7)
      = 5 + (4 + 7 + 10)
      = 5 + 21
      = 26

如上所述,以下代码生成整个表达式,在计算时,它等于26.它也可以用于生成逐步工作。

#include <iostream>
#include <string>

using namespace std;

string rec(string * N, int max) {
    if (max < 0)
        return "0";

    auto a = rec(N, max - 1), b = rec(N, max - 2);

    return "(" + N[max] + " + " + a + " + " + b + ")";
}

int main() {
    const int max = 5;
    string N[] = { "1", "2", "3", "4", "5" };
    auto f = rec(N, max - 1);

    cout << f << endl; 
    return 0;
}