C#递归算法实例:
计算数组{1,1,2,3,5,8.......} 第30位值,不用递归,我写出了以下这样的代码:
C#递归算法的使用,以下是代码:
// 阶乘
public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(6));
}
public static int factorial(int n) {
// 出口点
if (1==n) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
// 斐波那契数列
public class Fibonacci {
public static void main(String[] args) {
System.out.println(fibonacci(6));
}
// 斐波那契数列:(从第三项开始,后一项都是前两项的和)
// 1 1 2 3 5 8 13 ......
public static int fibonacci(int n) {
// 出口点
if (1==n || 2==n) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
}
// 遍历一个目录下的所有文件
public class FileList {
private static List<String> fileNameList = new ArrayList<String>();
public static void main(String[] args) {
String dir = "D://360Rec";
File file = new File(dir);
addAll(file);
for (String name : fileNameList) {
System.out.println(name);
}
}
public static void addAll(File file) {
// 出口点: 是文件或者是空目录
if (file.isFile() || file.list().length==0) {
fileNameList.add(file.getName());
} else {
File [] files = file.listFiles();
for (File f : files) {
addAll(f);
if (f.isDirectory() && f.list().length!=0) {
fileNameList.add(f.getName());
}
}
}
}
}
原文:http://www.cnblogs.com/weihengblogs/p/3736746.html