Java算法–第二章–查找与排序(2)递归基础
一、找重复
1.找到一种划分方法
2.找到递推公式或者等价转换
都是父问题转化为求解子问题
二、找变化的量
变化的量通常要作为参数
三、找出出口
代码:
package section02;
public class 递归基础 {
public static void main(String[] args) {
// 佩波那契
System.out.println(fib(5));
printHannuoiTower(4, "第一根", "第二根", "第三根");
}
/*
* 佩波那契数列
*/
static int fib(int n) {
if (n == 1 || n == 2)
return 1;
return fib(n - 1) + fib(n - 2);
}
/*
* 最大公约数
*/
static int gcd(int m, int n) {
if (n == 0)
return m;
return gcd(n, m % n);
}
/*
* 对数组进行插入排序
* 等价于:对数组的0到倒数第二个元素部分进行排序,然后把最后一个元素擦汗如到这个有序的部分中。
*/
static void insertSort(int[] arr, int k) {
if (k == 0)
return;
// 对前k - 1个元素排序
insertSort(arr, k - 1);
int x = arr[k];
int index = k - 1;
while (x < arr[index]) {
arr[index + 1] = arr[index];
index--;
}
arr[index + 1] = x;
}
/*
* 汉诺塔
*/
static void printHannuoiTower(int N, String from, String to, String help) {
if (N == 1) {
System.out.println("move " + N + " from " + from + " to " + to);
} else {
printHannuoiTower(N-1, from, help, to);//先把前N-1个盘子搬到辅助空间上去
System.out.println("move " + N + " from " + from + " to " + to);//N可以顺利到达target
printHannuoiTower(N-1, help, to, from);//让N-1从辅助空间回到原空间上去
}
}
}
输出:
5
move 1 from 第一根 to 第三根
move 2 from 第一根 to 第二根
move 1 from 第三根 to 第二根
move 3 from 第一根 to 第三根
move 1 from 第二根 to 第一根
move 2 from 第二根 to 第三根
move 1 from 第一根 to 第三根
move 4 from 第一根 to 第二根
move 1 from 第三根 to 第二根
move 2 from 第三根 to 第一根
move 1 from 第二根 to 第一根
move 3 from 第三根 to 第二根
move 1 from 第一根 to 第三根
move 2 from 第一根 to 第二根
move 1 from 第三根 to 第二根
汉诺塔:1~N从A移动到B,C作为辅助
等价于–>
1、1~N-1从A移动到C,B作为辅助
2、把N从A移动到B
3、1~N-1从C移动到B,A作为辅助