棘手的递归功能

时间:2012-11-01 03:40:18

标签: c# recursion

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.但任何人都可以解释原因吗?这令我感到困惑,因为它自称是2倍。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分:0)

这是一个小图像,显示树的递归。对已经计算过的孩子进行修剪enter image description here