面试题 08.06. 汉诺塔问题
n = 1 时,直接把盘子从 A 移到 C;
//n > 1 时,
先把上面 n - 1 个盘子从 A 移到 B(子问题,递归);
再将最大的盘子从 A 移到 C;
再将 B 上 n - 1 个盘子从 B 移到 C(子问题,递归)。
class Solution {
public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
int n=A.size();
hannoi(n,A,B,C);
}
public void hannoi(int n, List<Integer> A, List<Integer> B, List<Integer> C){
if(n == 1){
move(A, C);
}else{
hannoi(n-1, A, C, B);
move(A, C);
hannoi(n-1, B, A, C);
}
}
public void move(List<Integer> from, List<Integer> to){
Integer item=from.get(from.size()-1);
to.add(item);
from.remove(from.size()-1);
}
}