码农星球之最课程培训

一些递归使用场景的C#实现

递归的C#实现

1:计算数组{1,1,2,3,5,8.......} 第30位值

class Program
{
staticvoid Main(string[] args)
{
Console.WriteLine(Method1(
0));
Console.WriteLine(Method1(
1));
Console.WriteLine(Method1(
2));
Console.WriteLine(Method1(
3));
Console.WriteLine(
"……");
Console.WriteLine(Method1(
30));
}

staticint Method1(int n)
{
if (n <2)
{
return1;
}
else
{
return Method1(n -1) + Method1(n -2);
}
}
}

  

2:计算1+2+3+4+...+100的值

class Program
{
staticvoid Main(string[] args)
{
Console.WriteLine(Method1(
0));
Console.WriteLine(Method1(
1));
Console.WriteLine(Method1(
2));
Console.WriteLine(Method1(
3));
Console.WriteLine(
"……");
Console.WriteLine(Method1(
100));
}

staticint Method1(int i)
{
if (i ==0)
return0;
return Method1(i -1) + i;
}
}

  

3:计算1 -2 +3 +-4+ 5- 6 + 7 - 8 + 9的值

class Program
{
staticvoid Main(string[] args)
{
Console.WriteLine(Method1(
0));
Console.WriteLine(Method1(
1));
Console.WriteLine(Method1(
2));
Console.WriteLine(Method1(
3));
Console.WriteLine(
"……");
Console.WriteLine(Method1(
100));
}

//1 -2 +3 +-4+ 5- 6 + 7 - 8 + 9
staticint Method1(int i)
{
if (i ==0)
return0;
if (i ==1)
return1;
return i%2==0? Method1(i -1) - i : Method1(i -1) + i;
}
}

  

4:汉诺塔

staticvoid Main(string[] args)
{
Hanoi(
5, 'A', 'B', 'C');
Console.ReadLine();
}

publicstaticvoid Hanoi(int n, char A, char B, char C)
{
//汉诺塔问题
//将n个盘子从A座借助B座,移到C座
if (n ==1) Move(A, C);
else
{
Hanoi(n
-1, A, C, B);
Move(A, C);
Hanoi(n
-1, B, A, C);
}

}

publicstaticvoid Move(char startPlace, char endPlace)
{
Console.WriteLine(
"Move {0} To {1}", startPlace, endPlace);
}

  

posted @ 2011-08-18 11:02  陆敏技  阅读(...)  评论(...编辑  收藏
Web Counter
Coupon for Contacts