暴力递归-汉罗塔问题
暴力递归就是尝试 1,把问题转化为规模缩小了的同类问题的子问题
2,有明确的不需要继续进行递归的条件(base case) 3,有当得到了子问题的结果之后的决策过程 4,不记录每一个子问题的解 一定要学会怎么去尝试,因为这是动态规划的基础
汉罗塔问题
打印n层汉诺塔从最左边移动到最右边的全部过程
实现这个算法可以简单分为三个步骤:
(1)把n-1个盘子由A移到B;
(2)把第n个盘子由A移到C;
(3)把n-1个盘子由B移到C;
代码:
package Algorithms; public class Hanoi { public static void hanoi(int n) { if (n > 0) { func(n, n, "left", "mid", "right"); } } //1~i 圆盘 目标是from -> to,other是另外一个 public static void func(int rest, int down, String from, String help, String to) { if (rest == 1) { System.out.println("move " + down + " from " + from + " to " + to); } else { func(rest - 1, down - 1, from, to, help); //1、把n-1个盘子借助C由A移到B; func(1, down, from, help, to); //2、经过上面操作,A中只剩1个元素n,把第n个盘子从A移动到C(打印的过程) func(rest - 1, down - 1, help, from, to); //3、再把n-1个盘子借助A由B移到C; } } public static void main(String[] args) { int n = 3; hanoi(n); } } /** * move 1 from left to right * move 2 from left to mid * move 1 from right to mid * move 3 from left to right * move 1 from mid to left * move 2 from mid to right * move 1 from left to right */