面试题 08.06. 汉诺塔问题
题目详情
主要考察递归
采用Java实现。
class Solution {
public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
move(A.size(), A, B, C);
}
private void move(int count, List<Integer> source, List<Integer> temp, List<Integer> dest) {
if (count == 1) {
moveTopPlate(source, dest);
return;
}
// 将 source 柱子上的 n - 1 个盘子移动到temp,将dest作为辅助
move(count - 1, source, dest, temp);
moveTopPlate(source, dest);
// 将 temp 柱子上的 n - 1 个盘子移动到dest,将source作为辅助
move(count - 1, temp, source, dest);
}
private void moveTopPlate(List<Integer> source, List<Integer> dest) {
int topPlateIndex = source.size() - 1;
dest.add(source.remove(topPlateIndex));
// 为什么不使用dest.add(source.remove(0));——因为递归到最底层,需要取出source最顶部的盘子
}
}