0
public class look
{
    public int takeALook (int a)
    {
        if (a == 1)
            return 1;
        else if (a == 0)
            return 0;
        else
            return takeALook(a-2) + takeALook(a-1);

    }
}

主程序,

int a = 6;

look lk = new look();

int r = lk.takeALook(a);

Console.WriteLine("r is" + r);

答案是 8。但谁能解释为什么?这让我很困惑,因为它称自己为 2x。

4

4 回答 4

6
takeALook(0) == 0
takeALook(1) == 1
takeALook(2) == takeALook(0) + takeALook(1) == 0 + 1 == 1
takeALook(3) == takeALook(1) + takeALook(2) == 1 + 1 == 2
takeALook(4) == takeALook(2) + takeALook(3) == 1 + 2 == 3
takeALook(5) == takeALook(3) + takeALook(4) == 2 + 3 == 5
takeALook(6) == takeALook(4) + takeALook(5) == 3 + 5 == 8
于 2012-11-01T03:48:34.473 回答
3

归结起来是这样的:

takeALook(6) =>
(takeALook(4) + takeALook(5)) =>
(((2 + 3)) + ((3 + 4))) =>
((((0 + 1) + (1 + 2))) + (((1 + 2) + (2 + 3)))) =>
((((0 + 1) + (1 + (0 + 1)))) + (((1 + (0 + 1)) + ((0 + 1) + (1 + 2))))) =>
((((0 + 1) + (1 + (0 + 1)))) + (((1 + (0 + 1)) + ((0 + 1) + (1 + (0 + 1)))))) =>
0 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 0 + 1 + 1 + 0 + 1 =>
8
于 2012-11-01T03:47:33.290 回答
1

只需使用跟踪器修改您的程序,该跟踪器可能对任何递归函数都非常方便。

const string space = "  ";
static string StrMultiplier(string str,int multiplier)
{
    return string.Concat(Enumerable.Repeat(str,multiplier).ToArray());
}

static int F(int a,int level = 0)
{
    Console.WriteLine("{0}->F({1})",StrMultiplier(space,level),a);//Trace line
    if (a == 1)
        return 1;
    else if (a == 0)
        return 0;
    else
        return F(a-2,level + 1) + F(a-1,level+1);

}

结果:

->F(6)
  ->F(4)
    ->F(2)
      ->F(0)
      ->F(1)
    ->F(3)
      ->F(1)
      ->F(2)
        ->F(0)
        ->F(1)
  ->F(5)
    ->F(3)
      ->F(1)
      ->F(2)
        ->F(0)
        ->F(1)
    ->F(4)
      ->F(2)
        ->F(0)
        ->F(1)
      ->F(3)
        ->F(1)
        ->F(2)
          ->F(0)
          ->F(1)
于 2012-11-01T05:14:48.317 回答
0

这是一个将递归显示为树的小图像。修剪已经计算过的孩子在此处输入图像描述

于 2012-11-01T03:51:56.147 回答