简单的递归算法
static void Main(string[] args)
{
Console.WriteLine(Process1(30));
Console.ReadLine();
}
public static int Process1(int i)
{
//计算数组{1,1,2,3,5,8.......} 第30位值
if (i == 0) return 0;
if (i == 1) return 1;
else
return Process1(i - 1) + Process1(i - 2);
}
{
Console.WriteLine(Process1(30));
Console.ReadLine();
}
public static int Process1(int i)
{
//计算数组{1,1,2,3,5,8.......} 第30位值
if (i == 0) return 0;
if (i == 1) return 1;
else
return Process1(i - 1) + Process1(i - 2);
}
做了一些练习:
1. 计算1+2+3+4+...+100的值
static void Main(string[] args)
{
Console.WriteLine(Process2(100));
Console.ReadLine();
}
public static int Process2(int i)
{
//计算1+2+3+4+...+100的值
if (i == 0) return 0;
return Process2(i - 1) + i;
}
{
Console.WriteLine(Process2(100));
Console.ReadLine();
}
public static int Process2(int i)
{
//计算1+2+3+4+...+100的值
if (i == 0) return 0;
return Process2(i - 1) + i;
}
2. 计算1 -2 +3 +-4+ 5- 6 + 7 - 8 + 9的值
static void Main(string[] args)
{
Console.WriteLine(Process3(9) - Process3(8));
Console.ReadLine();
}
public static int Process3(int i)
{
//计算1 -2 +3 +-4+ 5- 6 + 7 - 8 + 9的值
if (i == 0) return 1;
if (i == 1) return 2;
else return Process3(i - 2) + i;
}
{
Console.WriteLine(Process3(9) - Process3(8));
Console.ReadLine();
}
public static int Process3(int i)
{
//计算1 -2 +3 +-4+ 5- 6 + 7 - 8 + 9的值
if (i == 0) return 1;
if (i == 1) return 2;
else return Process3(i - 2) + i;
}
3.汉诺塔问题
static void Main(string[] args)
{
Hanoi(5, 'A', 'B', 'C');
Console.ReadLine();
}
public static void 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);
}
}
public static void Move(char startPlace, char endPlace)
{
Console.WriteLine("Move {0} To {1}",startPlace,endPlace);
}
{
Hanoi(5, 'A', 'B', 'C');
Console.ReadLine();
}
public static void 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);
}
}
public static void Move(char startPlace, char endPlace)
{
Console.WriteLine("Move {0} To {1}",startPlace,endPlace);
}
4.用递归法将一个整数n转换成字符串,例如,输入483,就输出字符串"483".n的位数不确定,可以是任意位数的整数。
static void Main(string[] args)
{
IntToString(483, "");
Console.ReadLine();
}
public static void IntToString(int input,String output)
{
//用递归法将一个整数n转换成字符串,例如,输入483,就输出字符串"483".n的位数不确定,可以是任意位数的整数。
// String output = "";
output = input % 10+output;
if (input / 10 != 0)
{
IntToString(input / 10,output);
}
else Console.WriteLine(output);
}
{
IntToString(483, "");
Console.ReadLine();
}
public static void IntToString(int input,String output)
{
//用递归法将一个整数n转换成字符串,例如,输入483,就输出字符串"483".n的位数不确定,可以是任意位数的整数。
// String output = "";
output = input % 10+output;
if (input / 10 != 0)
{
IntToString(input / 10,output);
}
else Console.WriteLine(output);
}