c#递归算法
什么是递归函数/方法?
任何一个方法既可以调用其他方法也可以调用自己,而当这个方法调用自己时,我们就叫它递归函数或递归方法。
通常递归有两个特点:
1. 递归方法一直会调用自己直到某些条件被满足
2. 递归方法会有一些参数,而它会把一些新的参数值传递给自己
下面我打算介绍一些例子来帮助你更好的理解递归的风险和回报。
1. 阶乘
阶乘(!)是小于某个数的所有正整数的乘积。
0! = 1 1! = 1 2! = 2 * 1! = 2 3! = 3 * 2! = 6 ... n! = n * (n - 1)!
下面是计算阶乘的一种实现方法(没有递归):
public
long
Factorial(
int
n)
{
if
(n == 0)
return
1;
long
value = 1;
for
(
int
i = n; i > 0; i--)
{
value *= i;
}
return
value;
}
下面是用递归的方法实现计算阶乘,与之前的代码比起来它更简洁。
public
long
Factorial(
int
n)
{
if
(n == 0)
//限制条件,对该方法调用自己做了限制
return
1;
return
n * Factorial(n - 1);
}
2. Fibonacci数列
Fibonacci数列是按以下顺序排列的数字:
0,1,1,2,3,5,8,13,21,34,55,… 如果F
0
= 0 并且 F
1
= 1 那么F
n
= F
n-1
+ F
n-2
下面的方法就是用来计算Fn的(没有递归,性能好)
public
long
Fib(
int
n)
{
if
(n < 2)
return
n;
long
[] f =
new
long
[n+1];
f[0] = 0;
f[1] = 1;
for
(
int
i = 2; i <= n; i++)
{
f[i] = f[i - 1] + f[i - 2];
}
return
f[n];
}
如果我们使用递归方法,这个代码将更加简单,但性能很差。
public
long
Fib(
int
n)
{
if
(n == 0 || n == 1)
//满足条件
return
n;
return
Fib(k - 2) + Fib(k - 1);
}
3. 获取内部异常
如果你想获得innerException,那就选择递归方法吧,它很有用。
public
Exception GetInnerException(Exception ex)
{
return
(ex.InnerException ==
null
) ? ex : GetInnerException(ex.InnerException);
}
4. 查找文件
我在供你下载的示范项目中使用了递归,通过这个项目你可以搜索某个路径,并获得当前文件夹和其子文件夹中所有文件的路径。
private
Dictionary<
string
,
string
> errors =
new
Dictionary<
string
,
string
>();
private
List<
string
> result =
new
List<
string
>();
private
void
SearchForFiles(
string
path)
{
try
{
foreach
(
string
fileName
in
Directory.GetFiles(path))
//Gets all files in the current path
{
result.Add(fileName);
}
foreach
(
string
directory
in
Directory.GetDirectories(path))
//Gets all folders in the current path
{
SearchForFiles(directory);
//The methods calls itself with a new parameter, here!
}
}
catch
(System.Exception ex)
{
errors.Add(path, ex.Message);
//Stores Error Messages in a dictionary with path in key
}
}
这个方法似乎不需要满足任何条件,因为每个目录如果没有子目录,会自动遍历所有子文件。
总结:
1) 如果性能是非常重要的,请避免使用递归
2)如果递推方式不是很复杂的,请避免使用递归
3) 如果A和B都不满足,请不要犹豫,用递归吧。