您的位置:首页 > 职场人生

面试总结--递归

2010-09-25 21:58 169 查看
/**
*输出1,2,2,3,4,5的所有排列组合,4不能在第三位,3和5不能相邻
*/
public class Test12345 {
private int[] numbers = new int[] { 1, 2, 2, 3, 4, 5 };
public int n;
private String lastResult = "";
private boolean validate(String s) {
/*
* 在validate中使用了 if (s.compareTo(lastResult) <=
* 0)进行判断,由于按这种方法进行排列,如果这6个数是递增给出的
* ,那么排列的结果一定是递增的,但上述的6个数其中第2和第3个位置上都是2,因此
* ,如果出现了上一个结果不小于当前结果的情况,一定是有重复了,因此,要将这部分数过滤出去。
*/
if (s.compareTo(lastResult) <= 0)
return false;
if (s.charAt(2) == '4')
return false;
if (s.indexOf("35") >= 0 || s.indexOf("53") >= 0)
return false;
return true;
}
public void list(String index, String result) {
/**
* index参数表示已经选择过的数,用numbers数组的索引表示。如index="012",
* 表示numbers的前三个数已经被选择,也表示应该选择第四个数了,
* 而这第四个数应该从后三个数中选择。result参数表示临时的数字组合(这个数字组合最多是5个数字,
* 因为,如果到了6个数字,就表示已经有一个结果产生了)
*/
for (int i = 0; i < numbers.length; i++) {
if (index.indexOf(i + 48) < 0) {// i+48 ,当i=0时,正好是数字1的ASCII
String s = result + String.valueOf(numbers[i]);
if (s.length() == numbers.length) {
if (validate(s)) {
System.out.println(s);
lastResult = s;
n++;
}
break;
}
list(index + String.valueOf(i), s);
}
}
}
public static void main(String[] args) {
Test12345 t = new Test12345();
t.list("", "");
System.out.println("总数:" + t.n);
}


/**
* 一只猴子第一天摘下若干个桃子,当即吃了一半,不过瘾,又多吃了一个。第二天又将剩下的桃子吃了一半,又多吃了一个。以后每天都吃了前一天剩下的一半零一个。
* 第10天再想吃时,发现只剩下一个桃子。请问第一天猴子共摘了多少桃子?
*
* @author zengjie
*
*/
public class DiGui {
public static void main(String args[]) {
int peach = totalPeach(1);
System.out.println(peach);
}
public static int totalPeach(int day) {
if (day == 10) {
return 1;
}
return 2 * (totalPeach(day + 1) + 1);
}


/**
* 递归目录下的所有目录和文件名
*/
public class TestFile {
public static void listAllDir(String path) {
File file = new File(path);
if (file.isDirectory()) {
System.out.println(path);
String[] subPaths = file.list();
for (String s : subPaths) {
listAllDir(path + "/" + s);
}
} else {
System.out.println("" + path);
}
}
public static void main(String[] args) {
listAllDir("C:/签名工具");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: