目录
一.汉诺塔问题
1.问题概述
2.解法分析
总结:
(1)以C盘为中介,从A杆将1至n-1号盘移至B杆;
(2)将A杆中剩下的第n号盘移至C杆;
(3)以A杆为中介;从B杆将1至n-1号盘移至C杆。
(4) 一个盘子需要移动1次,两个盘子需要移动3次,三个盘子需要移动7次,不难得出,n个盘子需要移动2^n -1次
3.代码实现
public class TestDemo {
//1个盘子时:A->C 1
//2个盘子时:A->B A->C B->C 3
//3个盘子时:A->C A->B C->B A->C B->A B->C A->C 7
public static void move(char pos1,char pos2){
//模拟鼠标操作
System.out.print(pos1+"->"+pos2+" ");
}
/*
n 代表盘子个数
pos1 盘子的起始位置
pos2 盘子的中转位置
pos3 盘子的结束位置
*/
public static void hanoi(int n,char pos1,char pos2,char pos3){
if(n==1){
move(pos1,pos3);
}else{
hanoi(n-1,pos1,pos3,pos2);//n-1次的结束位置应该是B上面,除了最下面的盘子,其他全被移到了B上
move(pos1,pos3);//此时A上面仅剩下最下面的盘子,只需要将它移到C上
hanoi(n-1,pos2,pos1,pos3);//此时盘子数是没有最下面的盘子,我们仅需要把B上的盘子通过A移动到C上
}
}
public static void main(String[] args) {
hanoi(1,'A','B','C');
System.out.println();
hanoi(2,'A','B','C');
System.out.println();
hanoi(3,'A','B','C');
System.out.println();
hanoi(4,'A','B','C');
System.out.println();
hanoi(5,'A','B','C');
}
}
二.青蛙跳台阶问题
1.问题概述
一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法
2.解法分析
3.递归实现
public class TestDemo2 {
public static int frogJump(int n){//台阶数量
if(n==1 || n==2){
return n;
}else{
return frogJump(n-1)+frogJump(n-2);
}
}
public static void main(String[] args) {
System.out.println(frogJump(1));
System.out.println(frogJump(2));
System.out.println(frogJump(3));
System.out.println(frogJump(4));
System.out.println(frogJump(5));
}
}
4.迭代实现
public class TestDemo2 {
public static int frogJump(int n){//台阶数量
if(n==1 || n==2){
return n;
}
int f1 = 1;
int f2 = 2;
int f3 = 0;
for (int i = 3; i <=n ; i++) {
f3 = f1+f2;
f1 = f2;
f2 = f3;
}
return f3;
}
public static void main(String[] args) {
System.out.println(frogJump(1));
System.out.println(frogJump(2));
System.out.println(frogJump(3));
System.out.println(frogJump(4));
System.out.println(frogJump(5));
}
}