就以斐波那契数列为例,当时面试时问到了,很简单的题,问转化为非递归如何做,居然一时紧张没回答上来,太丢人了
using System;
namespace 练习
{
class test
{
//斐波那契数列:1 1 2 3 5 8 13 21 34...
//递归
public int f(int n)
{
if (n == 1 || n == 2)
return 1;
else
return f(n - 2) + f(n - 1);
}
//非递归
public int f1(int n)
{
if (n == 1 || n == 2)
return 1;
else
{
int x = 2;
int x1, x2;//保存x的前两个数,相比系统中递归方法用栈保存肯定会快很多
x1 = x2 = 1;
for (int i = 3; i <= n; i++)
{
x = x1 + x2;
x1 = x2;
x2 = x;
}
return x;
}
}
}
class 斐波那契递归与非递归
{
public static void Main(String[] Args)
{
test t=new test();
for (int i = 1; i <= 10; i++)
//Console.Write(t.f1(i) + " ");
Console.Write(t.f1(i) + " ");
Console.WriteLine();
}
}
}