递归算法设计的基本思想是:对于一个复杂的问题,把原问题分解为若干个相对简单的问题,继续下去直到子问题简单到能够直接求解,也就是说到了递推的出口,这样原问题就有递推得解。
/**
* 求从1加到5的和,代码如下: sum = 5+4+3+2+1
* @param n
* 递归算法要注意的两点:
* (1) 递归就是在方法里调用自己;
* (2)在使用递归算法时,必须要有一个明确的递归结束条件,称为递归出口。
*/
public static int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
/**
* 求n的阶乘,如下: 5!=5*4*3*2*1
* @param n
* @return
*/
public static int mul(int n){
if(n==1||n==0){
return 1;
}else{
return n*mul(n-1);
}
}
/**
* 有甲、乙、丙、丁四人,从甲开始到丁,一个比一个大1岁,已知丁10岁,问甲几岁?
* @param n
* one : age(2)+1
* two: age(3)+1
* three: age(4)+1
* four: 10
*/
public static int age(int n){
if(n==4){
return 10;
}else{
return age(n+1)+1;
}
}
/**
* 有一只兔子,从第三年开始每年生一只兔子,每只小兔从第3年每年生一只兔子。请编程实现在第n年的时候,共有多少只兔子?
*
* @param n
* @return
*/
public static int rabbit(int n) {
if (n <= 2) {
return 1;
} else {
return rabbit(n - 1) + rabbit(n - 2);
}
}
/**
* 有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
*
* @param n
* @return
*/
public static int cow(int n) {
if (n <= 1) {
return 1;
} else if (n == 2) {
return 2;
} else if (n == 3) {
return 3;
} else if (n == 4) {
return 4;
} else {
return cow(n - 1) + cow(n - 3);
}
}
for (int i = 1; i < 12; i++) {
// System.out.println(rabbit(i));
System.out.println(cow(i));
}
有一个梵塔,塔内有三个座A、B、C,A座上有诺干个盘子,盘子大小不等,大的在下,小的在上(如图)。
把这些个盘子从A座移到C座,中间可以借用B座但每次只能允许移动一个盘子,并且在移动过程中,3个座上的盘
子始终保持大盘在下,小盘在上。
描述简化:把A柱上的n个盘子移动到C柱,其中可以借用B柱。
/**
* 汉诺塔问题 递归程序
* @param n 盘子的个数
* @param a A塔
* @param b B塔
* @param c C塔
*/
public static void moveHano(int n,char a,char b,char c){
if(n==1){
//当n只有1个的时候直接从a移动到c
System.out.println("move disk "+n+"\tfrom"+a+"->to"+c);
}else{
moveHano(n-1, a, c, b); //第n-1个要从a通过c移动到b
System.out.println("move disk "+n+"\tfrom"+a+"->to"+c);
moveHano(n-1, b, a, c); //n-1个移动过来之后b变开始盘,b通过a移动到c
}
}